fantos commited on
Commit
eb5d82b
·
verified ·
1 Parent(s): 0e2318f

Create code-back.py

Browse files
Files changed (1) hide show
  1. code-back.py +373 -0
code-back.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import argparse
3
+ import os
4
+ import time
5
+ from os import path
6
+ import shutil
7
+ from datetime import datetime
8
+ from safetensors.torch import load_file
9
+ from huggingface_hub import hf_hub_download
10
+ import gradio as gr
11
+ import torch
12
+ from diffusers import FluxPipeline
13
+ from PIL import Image
14
+
15
+
16
+ # Setup and initialization code
17
+ cache_path = path.join(path.dirname(path.abspath(__file__)), "models")
18
+ # Use PERSISTENT_DIR environment variable for Spaces
19
+ PERSISTENT_DIR = os.environ.get("PERSISTENT_DIR", ".")
20
+ gallery_path = path.join(PERSISTENT_DIR, "gallery")
21
+
22
+ os.environ["TRANSFORMERS_CACHE"] = cache_path
23
+ os.environ["HF_HUB_CACHE"] = cache_path
24
+ os.environ["HF_HOME"] = cache_path
25
+
26
+ torch.backends.cuda.matmul.allow_tf32 = True
27
+
28
+ # Create gallery directory if it doesn't exist
29
+ if not path.exists(gallery_path):
30
+ os.makedirs(gallery_path, exist_ok=True)
31
+
32
+ class timer:
33
+ def __init__(self, method_name="timed process"):
34
+ self.method = method_name
35
+ def __enter__(self):
36
+ self.start = time.time()
37
+ print(f"{self.method} starts")
38
+ def __exit__(self, exc_type, exc_val, exc_tb):
39
+ end = time.time()
40
+ print(f"{self.method} took {str(round(end - self.start, 2))}s")
41
+
42
+ # Model initialization
43
+ if not path.exists(cache_path):
44
+ os.makedirs(cache_path, exist_ok=True)
45
+
46
+ pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
47
+ pipe.load_lora_weights(hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"))
48
+ pipe.fuse_lora(lora_scale=0.125)
49
+ pipe.to(device="cuda", dtype=torch.bfloat16)
50
+
51
+ css = """
52
+ footer {display: none !important}
53
+ .gradio-container {
54
+ max-width: 1200px;
55
+ margin: auto;
56
+ }
57
+ .contain {
58
+ background: rgba(255, 255, 255, 0.05);
59
+ border-radius: 12px;
60
+ padding: 20px;
61
+ }
62
+ .generate-btn {
63
+ background: linear-gradient(90deg, #4B79A1 0%, #283E51 100%) !important;
64
+ border: none !important;
65
+ color: white !important;
66
+ }
67
+ .generate-btn:hover {
68
+ transform: translateY(-2px);
69
+ box-shadow: 0 5px 15px rgba(0,0,0,0.2);
70
+ }
71
+ .title {
72
+ text-align: center;
73
+ font-size: 2.5em;
74
+ font-weight: bold;
75
+ margin-bottom: 1em;
76
+ background: linear-gradient(90deg, #4B79A1 0%, #283E51 100%);
77
+ -webkit-background-clip: text;
78
+ -webkit-text-fill-color: transparent;
79
+ }
80
+ /* Gallery specific styles */
81
+ #gallery {
82
+ width: 100% !important;
83
+ max-width: 100% !important;
84
+ overflow: visible !important;
85
+ }
86
+ #gallery > div {
87
+ width: 100% !important;
88
+ max-width: none !important;
89
+ }
90
+ #gallery > div > div {
91
+ width: 100% !important;
92
+ display: grid !important;
93
+ grid-template-columns: repeat(5, 1fr) !important;
94
+ gap: 16px !important;
95
+ padding: 16px !important;
96
+ }
97
+ .gallery-container {
98
+ background: rgba(255, 255, 255, 0.05);
99
+ border-radius: 8px;
100
+ margin-top: 10px;
101
+ width: 100% !important;
102
+ box-sizing: border-box !important;
103
+ }
104
+ /* Force gallery items to maintain aspect ratio */
105
+ .gallery-item {
106
+ width: 100% !important;
107
+ aspect-ratio: 1 !important;
108
+ overflow: hidden !important;
109
+ border-radius: 4px !important;
110
+ }
111
+ .gallery-item img {
112
+ width: 100% !important;
113
+ height: 100% !important;
114
+ object-fit: cover !important;
115
+ border-radius: 4px !important;
116
+ transition: transform 0.2s;
117
+ }
118
+ .gallery-item img:hover {
119
+ transform: scale(1.05);
120
+ }
121
+ /* Force output image container to full width */
122
+ .output-image {
123
+ width: 100% !important;
124
+ max-width: 100% !important;
125
+ }
126
+ /* Force container widths */
127
+ .contain > div {
128
+ width: 100% !important;
129
+ max-width: 100% !important;
130
+ }
131
+ .fixed-width {
132
+ width: 100% !important;
133
+ max-width: 100% !important;
134
+ }
135
+ /* Remove any horizontal scrolling */
136
+ .gallery-container::-webkit-scrollbar {
137
+ display: none !important;
138
+ }
139
+ .gallery-container {
140
+ -ms-overflow-style: none !important;
141
+ scrollbar-width: none !important;
142
+ }
143
+ /* Ensure consistent sizing for gallery wrapper */
144
+ #gallery > div {
145
+ width: 100% !important;
146
+ max-width: 100% !important;
147
+ }
148
+ #gallery > div > div {
149
+ width: 100% !important;
150
+ max-width: 100% !important;
151
+ }
152
+ """
153
+ def save_image(image):
154
+ """Save the generated image and return the path"""
155
+ try:
156
+ # Ensure gallery directory exists
157
+ if not os.path.exists(gallery_path):
158
+ try:
159
+ os.makedirs(gallery_path, exist_ok=True)
160
+ except Exception as e:
161
+ print(f"Failed to create gallery directory: {str(e)}")
162
+ return None
163
+
164
+ # Generate unique filename with timestamp and random suffix
165
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
166
+ random_suffix = os.urandom(4).hex()
167
+ filename = f"generated_{timestamp}_{random_suffix}.png"
168
+ filepath = os.path.join(gallery_path, filename)
169
+
170
+ try:
171
+ if isinstance(image, Image.Image):
172
+ image.save(filepath, "PNG", quality=100)
173
+ else:
174
+ image = Image.fromarray(image)
175
+ image.save(filepath, "PNG", quality=100)
176
+
177
+ if not os.path.exists(filepath):
178
+ print(f"Warning: Failed to verify saved image at {filepath}")
179
+ return None
180
+
181
+ return filepath
182
+ except Exception as e:
183
+ print(f"Failed to save image: {str(e)}")
184
+ return None
185
+
186
+ except Exception as e:
187
+ print(f"Error in save_image: {str(e)}")
188
+ return None
189
+
190
+
191
+ def load_gallery():
192
+ """Load all images from the gallery directory"""
193
+ try:
194
+ # Ensure gallery directory exists
195
+ os.makedirs(gallery_path, exist_ok=True)
196
+
197
+ # Get all image files and sort by modification time
198
+ image_files = []
199
+ for f in os.listdir(gallery_path):
200
+ if f.lower().endswith(('.png', '.jpg', '.jpeg')):
201
+ full_path = os.path.join(gallery_path, f)
202
+ image_files.append((full_path, os.path.getmtime(full_path)))
203
+
204
+ # Sort by modification time (newest first)
205
+ image_files.sort(key=lambda x: x[1], reverse=True)
206
+
207
+ # Return only the file paths
208
+ return [f[0] for f in image_files]
209
+ except Exception as e:
210
+ print(f"Error loading gallery: {str(e)}")
211
+ return []
212
+
213
+ # Create Gradio interface
214
+ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
215
+ gr.HTML('<div class="title">AI Image Generator</div>')
216
+ gr.HTML('<div style="text-align: center; margin-bottom: 2em; color: #666;">Create stunning images from your descriptions</div>')
217
+
218
+ with gr.Row():
219
+ with gr.Column(scale=3):
220
+ prompt = gr.Textbox(
221
+ label="Image Description",
222
+ placeholder="Describe the image you want to create...",
223
+ lines=3
224
+ )
225
+
226
+ with gr.Accordion("Advanced Settings", open=False):
227
+ with gr.Row():
228
+ height = gr.Slider(
229
+ label="Height",
230
+ minimum=256,
231
+ maximum=1152,
232
+ step=64,
233
+ value=1024
234
+ )
235
+ width = gr.Slider(
236
+ label="Width",
237
+ minimum=256,
238
+ maximum=1152,
239
+ step=64,
240
+ value=1024
241
+ )
242
+
243
+ with gr.Row():
244
+ steps = gr.Slider(
245
+ label="Inference Steps",
246
+ minimum=6,
247
+ maximum=25,
248
+ step=1,
249
+ value=8
250
+ )
251
+ scales = gr.Slider(
252
+ label="Guidance Scale",
253
+ minimum=0.0,
254
+ maximum=5.0,
255
+ step=0.1,
256
+ value=3.5
257
+ )
258
+
259
+ def get_random_seed():
260
+ return torch.randint(0, 1000000, (1,)).item()
261
+
262
+ seed = gr.Number(
263
+ label="Seed (random by default, set for reproducibility)",
264
+ value=get_random_seed(),
265
+ precision=0
266
+ )
267
+
268
+ randomize_seed = gr.Button("🎲 Randomize Seed", elem_classes=["generate-btn"])
269
+
270
+ generate_btn = gr.Button(
271
+ "✨ Generate Image",
272
+ elem_classes=["generate-btn"]
273
+ )
274
+
275
+ gr.HTML("""
276
+ <div style="margin-top: 1em; padding: 1em; border-radius: 8px; background: rgba(255, 255, 255, 0.05);">
277
+ <h4 style="margin: 0 0 0.5em 0;">Example Prompts:</h4>
278
+ <div style="background: rgba(75, 121, 161, 0.1); padding: 1em; border-radius: 8px; margin-bottom: 1em;">
279
+ <p style="font-weight: bold; margin: 0 0 0.5em 0;">🌅 Cinematic Landscape</p>
280
+ <p style="margin: 0; font-style: italic;">"A breathtaking mountain vista at golden hour, dramatic sunbeams piercing through clouds, snow-capped peaks reflecting warm light, ultra-high detail photography, artistically composed, award-winning landscape photo, shot on Hasselblad"</p>
281
+ </div>
282
+ <div style="background: rgba(75, 121, 161, 0.1); padding: 1em; border-radius: 8px; margin-bottom: 1em;">
283
+ <p style="font-weight: bold; margin: 0 0 0.5em 0;">🖼️ Fantasy Portrait</p>
284
+ <p style="margin: 0; font-style: italic;">"Ethereal portrait of an elven queen with flowing silver hair, adorned with luminescent crystals, intricate crown of twisted gold and moonstone, soft ethereal lighting, detailed facial features, fantasy art style, highly detailed, painted by Artgerm and Charlie Bowater"</p>
285
+ </div>
286
+ <div style="background: rgba(75, 121, 161, 0.1); padding: 1em; border-radius: 8px; margin-bottom: 1em;">
287
+ <p style="font-weight: bold; margin: 0 0 0.5em 0;">🌃 Cyberpunk Scene</p>
288
+ <p style="margin: 0; font-style: italic;">"Neon-lit cyberpunk street market in rain, holographic advertisements reflecting in puddles, street vendors with glowing cyber-augmentations, dense urban environment, atmospheric fog, cinematic lighting, inspired by Blade Runner 2049"</p>
289
+ </div>
290
+ <div style="background: rgba(75, 121, 161, 0.1); padding: 1em; border-radius: 8px; margin-bottom: 1em;">
291
+ <p style="font-weight: bold; margin: 0 0 0.5em 0;">🎨 Abstract Art</p>
292
+ <p style="margin: 0; font-style: italic;">"Vibrant abstract composition of flowing liquid colors, dynamic swirls of iridescent purples and teals, golden geometric patterns emerging from chaos, luxury art style, ultra-detailed, painted in oil on canvas, inspired by James Jean and Gustav Klimt"</p>
293
+ </div>
294
+ <div style="background: rgba(75, 121, 161, 0.1); padding: 1em; border-radius: 8px; margin-bottom: 1em;">
295
+ <p style="font-weight: bold; margin: 0 0 0.5em 0;">🌿 Macro Nature</p>
296
+ <p style="margin: 0; font-style: italic;">"Extreme macro photography of a dewdrop on a butterfly wing, rainbow light refraction, crystalline clarity, intricate wing scales visible, natural bokeh background, professional studio lighting, shot with Canon MP-E 65mm lens"</p>
297
+ </div>
298
+ </div>
299
+ """)
300
+
301
+ with gr.Column(scale=4, elem_classes=["fixed-width"]):
302
+ # Current generated image
303
+ output = gr.Image(
304
+ label="Generated Image",
305
+ elem_id="output-image",
306
+ elem_classes=["output-image", "fixed-width"]
307
+ )
308
+
309
+ # Gallery of generated images
310
+ gallery = gr.Gallery(
311
+ label="Generated Images Gallery",
312
+ show_label=True,
313
+ elem_id="gallery",
314
+ columns=[4],
315
+ rows=[2],
316
+ height="auto",
317
+ object_fit="cover",
318
+ elem_classes=["gallery-container", "fixed-width"]
319
+ )
320
+
321
+ # Load existing gallery images on startup
322
+ gallery.value = load_gallery()
323
+
324
+ @spaces.GPU
325
+ def process_and_save_image(height, width, steps, scales, prompt, seed):
326
+ global pipe
327
+ with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16), timer("inference"):
328
+ try:
329
+ generated_image = pipe(
330
+ prompt=[prompt],
331
+ generator=torch.Generator().manual_seed(int(seed)),
332
+ num_inference_steps=int(steps),
333
+ guidance_scale=float(scales),
334
+ height=int(height),
335
+ width=int(width),
336
+ max_sequence_length=256
337
+ ).images[0]
338
+
339
+ # Save the generated image
340
+ saved_path = save_image(generated_image)
341
+ if saved_path is None:
342
+ print("Warning: Failed to save generated image")
343
+
344
+ # Return both the generated image and updated gallery
345
+ return generated_image, load_gallery()
346
+ except Exception as e:
347
+ print(f"Error in image generation: {str(e)}")
348
+ return None, load_gallery()
349
+
350
+ # Connect the generation button to both the image output and gallery update
351
+ def update_seed():
352
+ return get_random_seed()
353
+
354
+ generate_btn.click(
355
+ process_and_save_image,
356
+ inputs=[height, width, steps, scales, prompt, seed],
357
+ outputs=[output, gallery]
358
+ )
359
+
360
+ # Add randomize seed button functionality
361
+ randomize_seed.click(
362
+ update_seed,
363
+ outputs=[seed]
364
+ )
365
+
366
+ # Also randomize seed after each generation
367
+ generate_btn.click(
368
+ update_seed,
369
+ outputs=[seed]
370
+ )
371
+
372
+ if __name__ == "__main__":
373
+ demo.launch(allowed_paths=[PERSISTENT_DIR])