fantos commited on
Commit
0c05b99
β€’
1 Parent(s): 5c16443

Delete code-back.py

Browse files
Files changed (1) hide show
  1. code-back.py +0 -388
code-back.py DELETED
@@ -1,388 +0,0 @@
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 diffusers.pipelines.stable_diffusion import safety_checker
14
- from PIL import Image
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
- def filter_prompt(prompt):
33
- # λΆ€μ μ ˆν•œ ν‚€μ›Œλ“œ λͺ©λ‘
34
- inappropriate_keywords = [
35
- # μŒλž€/성적 ν‚€μ›Œλ“œ
36
- "nude", "naked", "nsfw", "porn", "sex", "explicit", "adult", "xxx",
37
- "erotic", "sensual", "seductive", "provocative", "intimate",
38
- # 폭λ ₯적 ν‚€μ›Œλ“œ
39
- "violence", "gore", "blood", "death", "kill", "murder", "torture",
40
- # 기타 λΆ€μ μ ˆν•œ ν‚€μ›Œλ“œ
41
- "drug", "suicide", "abuse", "hate", "discrimination"
42
- ]
43
-
44
- prompt_lower = prompt.lower()
45
-
46
- # λΆ€μ μ ˆν•œ ν‚€μ›Œλ“œ 체크
47
- for keyword in inappropriate_keywords:
48
- if keyword in prompt_lower:
49
- return False, "λΆ€μ μ ˆν•œ λ‚΄μš©μ΄ ν¬ν•¨λœ ν”„λ‘¬ν”„νŠΈμž…λ‹ˆλ‹€."
50
-
51
- return True, prompt
52
-
53
- class timer:
54
- def __init__(self, method_name="timed process"):
55
- self.method = method_name
56
- def __enter__(self):
57
- self.start = time.time()
58
- print(f"{self.method} starts")
59
- def __exit__(self, exc_type, exc_val, exc_tb):
60
- end = time.time()
61
- print(f"{self.method} took {str(round(end - self.start, 2))}s")
62
-
63
- # Model initialization
64
- if not path.exists(cache_path):
65
- os.makedirs(cache_path, exist_ok=True)
66
-
67
- pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16)
68
- pipe.load_lora_weights(hf_hub_download("ByteDance/Hyper-SD", "Hyper-FLUX.1-dev-8steps-lora.safetensors"))
69
- pipe.fuse_lora(lora_scale=0.125)
70
- pipe.to(device="cuda", dtype=torch.bfloat16)
71
-
72
- # Add safety checker
73
- pipe.safety_checker = safety_checker.StableDiffusionSafetyChecker.from_pretrained("CompVis/stable-diffusion-safety-checker")
74
-
75
- css = """
76
- footer {display: none !important}
77
- .gradio-container {
78
- max-width: 1200px;
79
- margin: auto;
80
- }
81
- .contain {
82
- background: rgba(255, 255, 255, 0.05);
83
- border-radius: 12px;
84
- padding: 20px;
85
- }
86
- .generate-btn {
87
- background: linear-gradient(90deg, #4B79A1 0%, #283E51 100%) !important;
88
- border: none !important;
89
- color: white !important;
90
- }
91
- .generate-btn:hover {
92
- transform: translateY(-2px);
93
- box-shadow: 0 5px 15px rgba(0,0,0,0.2);
94
- }
95
- .title {
96
- text-align: center;
97
- font-size: 2.5em;
98
- font-weight: bold;
99
- margin-bottom: 1em;
100
- background: linear-gradient(90deg, #4B79A1 0%, #283E51 100%);
101
- -webkit-background-clip: text;
102
- -webkit-text-fill-color: transparent;
103
- }
104
- #gallery {
105
- width: 100% !important;
106
- max-width: 100% !important;
107
- overflow: visible !important;
108
- }
109
- #gallery > div {
110
- width: 100% !important;
111
- max-width: none !important;
112
- }
113
- #gallery > div > div {
114
- width: 100% !important;
115
- display: grid !important;
116
- grid-template-columns: repeat(5, 1fr) !important;
117
- gap: 16px !important;
118
- padding: 16px !important;
119
- }
120
- .gallery-container {
121
- background: rgba(255, 255, 255, 0.05);
122
- border-radius: 8px;
123
- margin-top: 10px;
124
- width: 100% !important;
125
- box-sizing: border-box !important;
126
- }
127
- .gallery-item {
128
- width: 100% !important;
129
- aspect-ratio: 1 !important;
130
- overflow: hidden !important;
131
- border-radius: 4px !important;
132
- }
133
- .gallery-item img {
134
- width: 100% !important;
135
- height: 100% !important;
136
- object-fit: cover !important;
137
- border-radius: 4px !important;
138
- transition: transform 0.2s;
139
- }
140
- .gallery-item img:hover {
141
- transform: scale(1.05);
142
- }
143
- .output-image {
144
- width: 100% !important;
145
- max-width: 100% !important;
146
- }
147
- .contain > div {
148
- width: 100% !important;
149
- max-width: 100% !important;
150
- }
151
- .fixed-width {
152
- width: 100% !important;
153
- max-width: 100% !important;
154
- }
155
- .gallery-container::-webkit-scrollbar {
156
- display: none !important;
157
- }
158
- .gallery-container {
159
- -ms-overflow-style: none !important;
160
- scrollbar-width: none !important;
161
- }
162
- #gallery > div {
163
- width: 100% !important;
164
- max-width: 100% !important;
165
- }
166
- #gallery > div > div {
167
- width: 100% !important;
168
- max-width: 100% !important;
169
- }
170
- """
171
-
172
- def save_image(image):
173
- """Save the generated image and return the path"""
174
- try:
175
- if not os.path.exists(gallery_path):
176
- try:
177
- os.makedirs(gallery_path, exist_ok=True)
178
- except Exception as e:
179
- print(f"Failed to create gallery directory: {str(e)}")
180
- return None
181
-
182
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
183
- random_suffix = os.urandom(4).hex()
184
- filename = f"generated_{timestamp}_{random_suffix}.png"
185
- filepath = os.path.join(gallery_path, filename)
186
-
187
- try:
188
- if isinstance(image, Image.Image):
189
- image.save(filepath, "PNG", quality=100)
190
- else:
191
- image = Image.fromarray(image)
192
- image.save(filepath, "PNG", quality=100)
193
-
194
- if not os.path.exists(filepath):
195
- print(f"Warning: Failed to verify saved image at {filepath}")
196
- return None
197
-
198
- return filepath
199
- except Exception as e:
200
- print(f"Failed to save image: {str(e)}")
201
- return None
202
-
203
- except Exception as e:
204
- print(f"Error in save_image: {str(e)}")
205
- return None
206
-
207
- def load_gallery():
208
- """Load all images from the gallery directory"""
209
- try:
210
- os.makedirs(gallery_path, exist_ok=True)
211
-
212
- image_files = []
213
- for f in os.listdir(gallery_path):
214
- if f.lower().endswith(('.png', '.jpg', '.jpeg')):
215
- full_path = os.path.join(gallery_path, f)
216
- image_files.append((full_path, os.path.getmtime(full_path)))
217
-
218
- image_files.sort(key=lambda x: x[1], reverse=True)
219
-
220
- return [f[0] for f in image_files]
221
- except Exception as e:
222
- print(f"Error loading gallery: {str(e)}")
223
- return []
224
-
225
- # Create Gradio interface
226
- with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
227
- gr.HTML('<div class="title">AI Image Generator</div>')
228
- gr.HTML('<div style="text-align: center; margin-bottom: 2em; color: #666;">Create stunning images from your descriptions</div>')
229
-
230
- gr.HTML("""
231
- <div style="color: red; margin-bottom: 1em; text-align: center; padding: 10px; background: rgba(255,0,0,0.1); border-radius: 8px;">
232
- ⚠️ μŒλž€ν•˜κ±°λ‚˜ λΆ€μ μ ˆν•œ λ‚΄μš©μ˜ μ΄λ―Έμ§€λŠ” 생성할 수 μ—†μŠ΅λ‹ˆλ‹€.
233
- </div>
234
- """)
235
-
236
- with gr.Row():
237
- with gr.Column(scale=3):
238
- prompt = gr.Textbox(
239
- label="Image Description",
240
- placeholder="Describe the image you want to create...",
241
- lines=3
242
- )
243
-
244
- with gr.Accordion("Advanced Settings", open=False):
245
- with gr.Row():
246
- height = gr.Slider(
247
- label="Height",
248
- minimum=256,
249
- maximum=1152,
250
- step=64,
251
- value=1024
252
- )
253
- width = gr.Slider(
254
- label="Width",
255
- minimum=256,
256
- maximum=1152,
257
- step=64,
258
- value=1024
259
- )
260
-
261
- with gr.Row():
262
- steps = gr.Slider(
263
- label="Inference Steps",
264
- minimum=6,
265
- maximum=25,
266
- step=1,
267
- value=8
268
- )
269
- scales = gr.Slider(
270
- label="Guidance Scale",
271
- minimum=0.0,
272
- maximum=5.0,
273
- step=0.1,
274
- value=3.5
275
- )
276
-
277
- def get_random_seed():
278
- return torch.randint(0, 1000000, (1,)).item()
279
-
280
- seed = gr.Number(
281
- label="Seed (random by default, set for reproducibility)",
282
- value=get_random_seed(),
283
- precision=0
284
- )
285
-
286
- randomize_seed = gr.Button("🎲 Randomize Seed", elem_classes=["generate-btn"])
287
-
288
- generate_btn = gr.Button(
289
- "✨ Generate Image",
290
- elem_classes=["generate-btn"]
291
- )
292
-
293
- gr.HTML("""
294
- <div style="margin-top: 1em; padding: 1em; border-radius: 8px; background: rgba(255, 255, 255, 0.05);">
295
- <h4 style="margin: 0 0 0.5em 0;">Example Prompts:</h4>
296
- <div style="background: rgba(75, 121, 161, 0.1); padding: 1em; border-radius: 8px; margin-bottom: 1em;">
297
- <p style="font-weight: bold; margin: 0 0 0.5em 0;">πŸŒ… Cinematic Landscape</p>
298
- <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>
299
- </div>
300
- <div style="background: rgba(75, 121, 161, 0.1); padding: 1em; border-radius: 8px; margin-bottom: 1em;">
301
- <p style="font-weight: bold; margin: 0 0 0.5em 0;">πŸ–ΌοΈ Fantasy Portrait</p>
302
- <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>
303
- </div>
304
- <div style="background: rgba(75, 121, 161, 0.1); padding: 1em; border-radius: 8px; margin-bottom: 1em;">
305
- <p style="font-weight: bold; margin: 0 0 0.5em 0;">πŸŒƒ Cyberpunk Scene</p>
306
- <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>
307
- </div>
308
- <div style="background: rgba(75, 121, 161, 0.1); padding: 1em; border-radius: 8px; margin-bottom: 1em;">
309
- <p style="font-weight: bold; margin: 0 0 0.5em 0;">🎨 Abstract Art</p>
310
- <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>
311
- </div>
312
- <div style="background: rgba(75, 121, 161, 0.1); padding: 1em; border-radius: 8px; margin-bottom: 1em;">
313
- <p style="font-weight: bold; margin: 0 0 0.5em 0;">🌿 Macro Nature</p>
314
- <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>
315
- </div>
316
- </div>
317
- """)
318
-
319
- with gr.Column(scale=4, elem_classes=["fixed-width"]):
320
- output = gr.Image(
321
- label="Generated Image",
322
- elem_id="output-image",
323
- elem_classes=["output-image", "fixed-width"]
324
- )
325
-
326
- gallery = gr.Gallery(
327
- label="Generated Images Gallery",
328
- show_label=True,
329
- elem_id="gallery",
330
- columns=[4],
331
- rows=[2],
332
- height="auto",
333
- object_fit="cover",
334
- elem_classes=["gallery-container", "fixed-width"]
335
- )
336
-
337
- gallery.value = load_gallery()
338
-
339
- @spaces.GPU
340
- def process_and_save_image(height, width, steps, scales, prompt, seed):
341
- # ν”„λ‘¬ν”„νŠΈ 필터링
342
- is_safe, filtered_prompt = filter_prompt(prompt)
343
- if not is_safe:
344
- gr.Warning("λΆ€μ μ ˆν•œ λ‚΄μš©μ΄ ν¬ν•¨λœ ν”„λ‘¬ν”„νŠΈμž…λ‹ˆλ‹€.")
345
- return None, load_gallery()
346
-
347
- with torch.inference_mode(), torch.autocast("cuda", dtype=torch.bfloat16), timer("inference"):
348
- try:
349
- generated_image = pipe(
350
- prompt=[filtered_prompt],
351
- generator=torch.Generator().manual_seed(int(seed)),
352
- num_inference_steps=int(steps),
353
- guidance_scale=float(scales),
354
- height=int(height),
355
- width=int(width),
356
- max_sequence_length=256
357
- ).images[0]
358
-
359
- saved_path = save_image(generated_image)
360
- if saved_path is None:
361
- print("Warning: Failed to save generated image")
362
-
363
- return generated_image, load_gallery()
364
- except Exception as e:
365
- print(f"Error in image generation: {str(e)}")
366
- return None, load_gallery()
367
-
368
- def update_seed():
369
- return get_random_seed()
370
-
371
- generate_btn.click(
372
- process_and_save_image,
373
- inputs=[height, width, steps, scales, prompt, seed],
374
- outputs=[output, gallery]
375
- )
376
-
377
- randomize_seed.click(
378
- update_seed,
379
- outputs=[seed]
380
- )
381
-
382
- generate_btn.click(
383
- update_seed,
384
- outputs=[seed]
385
- )
386
-
387
- if __name__ == "__main__":
388
- demo.launch(allowed_paths=[PERSISTENT_DIR])