seawolf2357 commited on
Commit
35ac15a
·
verified ·
1 Parent(s): ee33d4a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +282 -19
app.py CHANGED
@@ -1,23 +1,286 @@
 
1
  import os
2
- import spaces
 
3
  import gradio as gr
4
  import numpy as np
5
- from PIL import Image
6
- import random
7
- from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler, DiffusionPipeline
8
- import re
9
- from cohere import ClientV2
10
  import torch
11
- import logging
12
-
13
- import ast #추가 삽입, requirements: albumentations 추가
14
- script_repr = os.getenv("APP")
15
- if script_repr is None:
16
- print("Error: Environment variable 'APP' not set.")
17
- sys.exit(1)
18
-
19
- try:
20
- exec(script_repr)
21
- except Exception as e:
22
- print(f"Error executing script: {e}")
23
- sys.exit(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
  import os
3
+ import uuid
4
+ from datetime import datetime
5
  import gradio as gr
6
  import numpy as np
7
+ import spaces
 
 
 
 
8
  import torch
9
+ from diffusers import DiffusionPipeline
10
+ from PIL import Image
11
+
12
+ # Create permanent storage directory
13
+ SAVE_DIR = "saved_images" # Gradio will handle the persistence
14
+ if not os.path.exists(SAVE_DIR):
15
+ os.makedirs(SAVE_DIR, exist_ok=True)
16
+
17
+ device = "cuda" if torch.cuda.is_available() else "cpu"
18
+ repo_id = "black-forest-labs/FLUX.1-dev"
19
+ adapter_id = "seawolf2357/nsfw-detection" # Changed to Renoir model
20
+
21
+ pipeline = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch.bfloat16)
22
+ pipeline.load_lora_weights(adapter_id)
23
+ pipeline = pipeline.to(device)
24
+
25
+ MAX_SEED = np.iinfo(np.int32).max
26
+ MAX_IMAGE_SIZE = 1024
27
+
28
+ def save_generated_image(image, prompt):
29
+ # Generate unique filename with timestamp
30
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
31
+ unique_id = str(uuid.uuid4())[:8]
32
+ filename = f"{timestamp}_{unique_id}.png"
33
+ filepath = os.path.join(SAVE_DIR, filename)
34
+
35
+ # Save the image
36
+ image.save(filepath)
37
+
38
+ # Save metadata
39
+ metadata_file = os.path.join(SAVE_DIR, "metadata.txt")
40
+ with open(metadata_file, "a", encoding="utf-8") as f:
41
+ f.write(f"{filename}|{prompt}|{timestamp}\n")
42
+
43
+ return filepath
44
+
45
+ def load_generated_images():
46
+ if not os.path.exists(SAVE_DIR):
47
+ return []
48
+
49
+ # Load all images from the directory
50
+ image_files = [os.path.join(SAVE_DIR, f) for f in os.listdir(SAVE_DIR)
51
+ if f.endswith(('.png', '.jpg', '.jpeg', '.webp'))]
52
+ # Sort by creation time (newest first)
53
+ image_files.sort(key=lambda x: os.path.getctime(x), reverse=True)
54
+ return image_files
55
+
56
+ def load_predefined_images():
57
+ predefined_images = [
58
+ "assets/r1.webp",
59
+ "assets/r2.webp",
60
+ "assets/r3.webp",
61
+ "assets/r4.webp",
62
+ "assets/r5.webp",
63
+ "assets/r6.webp",
64
+ ]
65
+ return predefined_images
66
+
67
+ @spaces.GPU(duration=120)
68
+ def inference(
69
+ prompt: str,
70
+ seed: int,
71
+ randomize_seed: bool,
72
+ width: int,
73
+ height: int,
74
+ guidance_scale: float,
75
+ num_inference_steps: int,
76
+ lora_scale: float,
77
+ progress: gr.Progress = gr.Progress(track_tqdm=True),
78
+ ):
79
+ if randomize_seed:
80
+ seed = random.randint(0, MAX_SEED)
81
+ generator = torch.Generator(device=device).manual_seed(seed)
82
+
83
+ image = pipeline(
84
+ prompt=prompt,
85
+ guidance_scale=guidance_scale,
86
+ num_inference_steps=num_inference_steps,
87
+ width=width,
88
+ height=height,
89
+ generator=generator,
90
+ joint_attention_kwargs={"scale": lora_scale},
91
+ ).images[0]
92
+
93
+ # Save the generated image
94
+ filepath = save_generated_image(image, prompt)
95
+
96
+ # Return the image, seed, and updated gallery
97
+ return image, seed, load_generated_images()
98
+
99
+ examples = [
100
+ "nsfw painting of a lively outdoor dance scene at Moulin de la Galette, with dappled sunlight filtering through trees, illuminating well-dressed Parisians enjoying a summer afternoon. Couples dance while others socialize at tables, capturing the joie de vivre of 1870s Montmartre. [trigger]",
101
+ "nsfw intimate portrait of a young woman with rosy cheeks and lips, soft blonde hair, and a gentle smile. She wears a vibrant blue dress against a background of lush flowers and greenery, showcasing his mastery of depicting feminine beauty with warm, luminous skin tones. [trigger]",
102
+ "nsfw painting of two young girls seated at a piano, captured in his distinctive soft focus style. The scene shows one girl playing while the other stands beside her, both wearing delicate white dresses. The interior setting features warm colors and loose brushwork typical of his mature period. [trigger]",
103
+ "nsfw painting of an elegant boating party, with fashionably dressed men and women relaxing on a restaurant terrace overlooking the Seine. The scene captures the leisurely atmosphere of 1880s French society, with sparkling water reflections and a bright, airy palette of blues, whites, and warm flesh tones. [trigger]",
104
+ "nsfw painting of a sun-dappled garden scene with children playing. The composition features vibrant flowers in full bloom, lush greenery, and Renoir's characteristic luminous treatment of sunlight filtering through foliage, creating patches of brilliant color across the canvas. [trigger]",
105
+ "nsfw depiction of bathers by a riverbank, with several female figures arranged in a harmonious composition. The painting showcases his later style with fuller figures rendered in pearlescent flesh tones against a backdrop of shimmering water and verdant landscape, demonstrating his unique approach to the nude figure in nature. [trigger]"
106
+ ]
107
+
108
+ # Brighter custom CSS with vibrant colors
109
+ custom_css = """
110
+ :root {
111
+ --color-primary: #FF9E6C;
112
+ --color-secondary: #FFD8A9;
113
+ }
114
+ footer {
115
+ visibility: hidden;
116
+ }
117
+ .gradio-container {
118
+ background: linear-gradient(to right, #FFF4E0, #FFEDDB);
119
+ }
120
+ .title {
121
+ color: #E25822 !important;
122
+ font-size: 2.5rem !important;
123
+ font-weight: 700 !important;
124
+ text-align: center;
125
+ margin: 1rem 0;
126
+ text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
127
+ }
128
+ .subtitle {
129
+ color: #2B3A67 !important;
130
+ font-size: 1.2rem !important;
131
+ text-align: center;
132
+ margin-bottom: 2rem;
133
+ }
134
+ .model-description {
135
+ background-color: rgba(255, 255, 255, 0.7);
136
+ border-radius: 10px;
137
+ padding: 20px;
138
+ margin: 20px 0;
139
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
140
+ border-left: 5px solid #E25822;
141
+ }
142
+ button.primary {
143
+ background-color: #E25822 !important;
144
+ }
145
+ button:hover {
146
+ transform: translateY(-2px);
147
+ box-shadow: 0 5px 15px rgba(0,0,0,0.1);
148
+ }
149
+ .tabs {
150
+ margin-top: 20px;
151
+ }
152
+ .gallery {
153
+ background-color: rgba(255, 255, 255, 0.5);
154
+ border-radius: 10px;
155
+ padding: 10px;
156
+ }
157
+ """
158
+
159
+ with gr.Blocks(css=custom_css, analytics_enabled=False) as demo:
160
+ gr.HTML('<div class="title">nsfw detection STUDIO</div>')
161
+
162
+ # Model description with the requested content
163
+ with gr.Group(elem_classes="model-description"):
164
+
165
+ with gr.Tabs(elem_classes="tabs") as tabs:
166
+ with gr.Tab("Generation"):
167
+ with gr.Column(elem_id="col-container"):
168
+ with gr.Row():
169
+ prompt = gr.Text(
170
+ label="Prompt",
171
+ show_label=False,
172
+ max_lines=1,
173
+ placeholder="Enter your prompt (add [trigger] at the end)",
174
+ container=False,
175
+ )
176
+ run_button = gr.Button("Generate", variant="primary", scale=0)
177
+
178
+ result = gr.Image(label="Result", show_label=False)
179
+
180
+ with gr.Accordion("Advanced Settings", open=False):
181
+ seed = gr.Slider(
182
+ label="Seed",
183
+ minimum=0,
184
+ maximum=MAX_SEED,
185
+ step=1,
186
+ value=42,
187
+ )
188
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
189
+
190
+ with gr.Row():
191
+ width = gr.Slider(
192
+ label="Width",
193
+ minimum=256,
194
+ maximum=MAX_IMAGE_SIZE,
195
+ step=32,
196
+ value=1024,
197
+ )
198
+ height = gr.Slider(
199
+ label="Height",
200
+ minimum=256,
201
+ maximum=MAX_IMAGE_SIZE,
202
+ step=32,
203
+ value=768,
204
+ )
205
+
206
+ with gr.Row():
207
+ guidance_scale = gr.Slider(
208
+ label="Guidance scale",
209
+ minimum=0.0,
210
+ maximum=10.0,
211
+ step=0.1,
212
+ value=3.5,
213
+ )
214
+ num_inference_steps = gr.Slider(
215
+ label="Number of inference steps",
216
+ minimum=1,
217
+ maximum=50,
218
+ step=1,
219
+ value=30,
220
+ )
221
+ lora_scale = gr.Slider(
222
+ label="LoRA scale",
223
+ minimum=0.0,
224
+ maximum=1.0,
225
+ step=0.1,
226
+ value=1.0,
227
+ )
228
+
229
+ gr.Examples(
230
+ examples=examples,
231
+ inputs=[prompt],
232
+ outputs=[result, seed],
233
+ )
234
+
235
+ with gr.Tab("Gallery"):
236
+ gallery_header = gr.Markdown("### Your Generated Images")
237
+ generated_gallery = gr.Gallery(
238
+ label="Generated Images",
239
+ columns=3,
240
+ show_label=False,
241
+ value=load_generated_images(),
242
+ elem_id="generated_gallery",
243
+ elem_classes="gallery",
244
+ height="auto"
245
+ )
246
+ refresh_btn = gr.Button("🔄 Refresh Gallery", variant="primary")
247
+
248
+ # Add sample gallery section at the bottom
249
+ gr.Markdown("### Pierre-Auguste Renoir Style Examples")
250
+ predefined_gallery = gr.Gallery(
251
+ label="Sample Images",
252
+ columns=3,
253
+ rows=2,
254
+ show_label=False,
255
+ value=load_predefined_images(),
256
+ elem_classes="gallery"
257
+ )
258
+
259
+ # Event handlers
260
+ def refresh_gallery():
261
+ return load_generated_images()
262
+
263
+ refresh_btn.click(
264
+ fn=refresh_gallery,
265
+ inputs=None,
266
+ outputs=generated_gallery,
267
+ )
268
+
269
+ gr.on(
270
+ triggers=[run_button.click, prompt.submit],
271
+ fn=inference,
272
+ inputs=[
273
+ prompt,
274
+ seed,
275
+ randomize_seed,
276
+ width,
277
+ height,
278
+ guidance_scale,
279
+ num_inference_steps,
280
+ lora_scale,
281
+ ],
282
+ outputs=[result, seed, generated_gallery],
283
+ )
284
+
285
+ demo.queue()
286
+ demo.launch()