prithivMLmods commited on
Commit
ee317af
·
verified ·
1 Parent(s): f2cb7c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +279 -229
app.py CHANGED
@@ -1,230 +1,280 @@
1
- import spaces
2
- import gradio as gr
3
- import torch
4
- from PIL import Image
5
- from diffusers import DiffusionPipeline
6
- import random
7
- import uuid
8
- from typing import Tuple
9
- import numpy as np
10
-
11
- DESCRIPTIONz = """## FLUX REALPIX 🔥"""
12
-
13
- def save_image(img):
14
- unique_name = str(uuid.uuid4()) + ".png"
15
- img.save(unique_name)
16
- return unique_name
17
-
18
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
19
- if randomize_seed:
20
- seed = random.randint(0, MAX_SEED)
21
- return seed
22
-
23
- MAX_SEED = np.iinfo(np.int32).max
24
-
25
- if not torch.cuda.is_available():
26
- DESCRIPTIONz += "\n<p>⚠️Running on CPU, This may not work on CPU.</p>"
27
-
28
- base_model = "black-forest-labs/FLUX.1-dev"
29
- pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=torch.bfloat16)
30
-
31
- lora_repo = "prithivMLmods/Canopus-LoRA-Flux-FaceRealism"
32
- trigger_word = "realism" # Leave trigger_word blank if not used.
33
- pipe.load_lora_weights(lora_repo)
34
-
35
- pipe.to("cuda")
36
-
37
- style_list = [
38
- {
39
- "name": "3840 x 2160",
40
- "prompt": "hyper-realistic 8K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
41
- },
42
- {
43
- "name": "2560 x 1440",
44
- "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
45
- },
46
- {
47
- "name": "HD+",
48
- "prompt": "hyper-realistic 2K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
49
- },
50
- {
51
- "name": "Style Zero",
52
- "prompt": "{prompt}",
53
- },
54
- ]
55
-
56
- styles = {k["name"]: k["prompt"] for k in style_list}
57
-
58
- DEFAULT_STYLE_NAME = "3840 x 2160"
59
- STYLE_NAMES = list(styles.keys())
60
-
61
- def apply_style(style_name: str, positive: str) -> str:
62
- return styles.get(style_name, styles[DEFAULT_STYLE_NAME]).replace("{prompt}", positive)
63
-
64
- @spaces.GPU(duration=60, enable_queue=True)
65
- def generate(
66
- prompt: str,
67
- seed: int = 0,
68
- width: int = 1024,
69
- height: int = 1024,
70
- guidance_scale: float = 3,
71
- randomize_seed: bool = False,
72
- style_name: str = DEFAULT_STYLE_NAME,
73
- progress=gr.Progress(track_tqdm=True),
74
- ):
75
- seed = int(randomize_seed_fn(seed, randomize_seed))
76
-
77
- positive_prompt = apply_style(style_name, prompt)
78
-
79
- if trigger_word:
80
- positive_prompt = f"{trigger_word} {positive_prompt}"
81
-
82
- images = pipe(
83
- prompt=positive_prompt,
84
- width=width,
85
- height=height,
86
- guidance_scale=guidance_scale,
87
- num_inference_steps=16,
88
- num_images_per_prompt=1,
89
- output_type="pil",
90
- ).images
91
- image_paths = [save_image(img) for img in images]
92
- print(image_paths)
93
- return image_paths, seed
94
-
95
-
96
- def load_predefined_images():
97
- predefined_images = [
98
- "assets/11.png",
99
- "assets/22.png",
100
- "assets/33.png",
101
- "assets/44.png",
102
- "assets/55.webp",
103
- "assets/66.png",
104
- "assets/77.png",
105
- "assets/88.png",
106
- "assets/99.png",
107
- ]
108
- return predefined_images
109
-
110
-
111
-
112
- examples = [
113
- "A portrait of an attractive woman in her late twenties with light brown hair and purple, wearing large a a yellow sweater. She is looking directly at the camera, standing outdoors near trees.. --ar 128:85 --v 6.0 --style raw",
114
- "A photo of the model wearing a white bodysuit and beige trench coat, posing in front of a train station with hands on head, soft light, sunset, fashion photography, high resolution, 35mm lens, f/22, natural lighting, global illumination. --ar 85:128 --v 6.0 --style raw",
115
- ]
116
-
117
-
118
- css = '''
119
- .gradio-container{max-width: 575px !important}
120
- h1{text-align:center}
121
- footer {
122
- visibility: hidden
123
- }
124
- '''
125
-
126
- with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
127
- gr.Markdown(DESCRIPTIONz)
128
- with gr.Group():
129
- with gr.Row():
130
- prompt = gr.Text(
131
- label="Prompt",
132
- show_label=False,
133
- max_lines=1,
134
- placeholder="Enter your prompt with realism tag!",
135
- container=False,
136
- )
137
- run_button = gr.Button("Run", scale=0)
138
- result = gr.Gallery(label="Result", columns=1, preview=True, show_label=False)
139
-
140
- with gr.Accordion("Advanced options", open=False, visible=True):
141
- seed = gr.Slider(
142
- label="Seed",
143
- minimum=0,
144
- maximum=MAX_SEED,
145
- step=1,
146
- value=0,
147
- visible=True
148
- )
149
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
150
-
151
- with gr.Row(visible=True):
152
- width = gr.Slider(
153
- label="Width",
154
- minimum=512,
155
- maximum=2048,
156
- step=64,
157
- value=1024,
158
- )
159
- height = gr.Slider(
160
- label="Height",
161
- minimum=512,
162
- maximum=2048,
163
- step=64,
164
- value=1024,
165
- )
166
-
167
- with gr.Row():
168
- guidance_scale = gr.Slider(
169
- label="Guidance Scale",
170
- minimum=0.1,
171
- maximum=20.0,
172
- step=0.1,
173
- value=3.0,
174
- )
175
- num_inference_steps = gr.Slider(
176
- label="Number of inference steps",
177
- minimum=1,
178
- maximum=40,
179
- step=1,
180
- value=16,
181
- )
182
-
183
- style_selection = gr.Radio(
184
- show_label=True,
185
- container=True,
186
- interactive=True,
187
- choices=STYLE_NAMES,
188
- value=DEFAULT_STYLE_NAME,
189
- label="Quality Style",
190
- )
191
-
192
-
193
-
194
- gr.Examples(
195
- examples=examples,
196
- inputs=prompt,
197
- outputs=[result, seed],
198
- fn=generate,
199
- cache_examples=False,
200
- )
201
-
202
- gr.on(
203
- triggers=[
204
- prompt.submit,
205
- run_button.click,
206
- ],
207
- fn=generate,
208
- inputs=[
209
- prompt,
210
- seed,
211
- width,
212
- height,
213
- guidance_scale,
214
- randomize_seed,
215
- style_selection,
216
- ],
217
- outputs=[result, seed],
218
- api_name="run",
219
- )
220
-
221
- gr.Markdown("### Generated Images")
222
- predefined_gallery = gr.Gallery(label="Generated Images", columns=3, show_label=False, value=load_predefined_images())
223
- gr.Markdown("**Disclaimer/Note:**")
224
-
225
- gr.Markdown("🔥This space provides realistic image generation, which works better for human faces and portraits. Realistic trigger works properly, better for photorealistic trigger words, close-up shots, face diffusion, male, female characters.")
226
-
227
- gr.Markdown("🔥users are accountable for the content they generate and are responsible for ensuring it meets appropriate ethical standards.")
228
-
229
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230
  demo.queue(max_size=40).launch()
 
1
+ import spaces
2
+ import gradio as gr
3
+ import torch
4
+ from PIL import Image
5
+ from diffusers import DiffusionPipeline
6
+ import random
7
+ import uuid
8
+ from typing import Tuple
9
+ import numpy as np
10
+
11
+ DESCRIPTIONz = """## FLUX REALPIX 🔥"""
12
+
13
+ def save_image(img):
14
+ unique_name = str(uuid.uuid4()) + ".png"
15
+ img.save(unique_name)
16
+ return unique_name
17
+
18
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
19
+ if randomize_seed:
20
+ seed = random.randint(0, MAX_SEED)
21
+ return seed
22
+
23
+ MAX_SEED = np.iinfo(np.int32).max
24
+
25
+ if not torch.cuda.is_available():
26
+ DESCRIPTIONz += "\n<p>⚠️Running on CPU, This may not work on CPU.</p>"
27
+
28
+ base_model = "black-forest-labs/FLUX.1-dev"
29
+ pipe = DiffusionPipeline.from_pretrained(base_model, torch_dtype=torch.bfloat16)
30
+
31
+ lora_repo = "prithivMLmods/Canopus-LoRA-Flux-FaceRealism"
32
+ trigger_word = "realism" # Leave trigger_word blank if not used.
33
+ pipe.load_lora_weights(lora_repo)
34
+
35
+ pipe.to("cuda")
36
+
37
+ style_list = [
38
+ {
39
+ "name": "3840 x 2160",
40
+ "prompt": "hyper-realistic 8K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
41
+ },
42
+ {
43
+ "name": "2560 x 1440",
44
+ "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
45
+ },
46
+ {
47
+ "name": "HD+",
48
+ "prompt": "hyper-realistic 2K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
49
+ },
50
+ {
51
+ "name": "Style Zero",
52
+ "prompt": "{prompt}",
53
+ },
54
+ ]
55
+
56
+ styles = {k["name"]: k["prompt"] for k in style_list}
57
+
58
+ DEFAULT_STYLE_NAME = "3840 x 2160"
59
+ STYLE_NAMES = list(styles.keys())
60
+
61
+ def apply_style(style_name: str, positive: str) -> str:
62
+ return styles.get(style_name, styles[DEFAULT_STYLE_NAME]).replace("{prompt}", positive)
63
+
64
+ @spaces.GPU(duration=60, enable_queue=True)
65
+ def generate(
66
+ prompt: str,
67
+ seed: int = 0,
68
+ width: int = 1024,
69
+ height: int = 1024,
70
+ guidance_scale: float = 3,
71
+ randomize_seed: bool = False,
72
+ style_name: str = DEFAULT_STYLE_NAME,
73
+ progress=gr.Progress(track_tqdm=True),
74
+ ):
75
+ seed = int(randomize_seed_fn(seed, randomize_seed))
76
+
77
+ positive_prompt = apply_style(style_name, prompt)
78
+
79
+ if trigger_word:
80
+ positive_prompt = f"{trigger_word} {positive_prompt}"
81
+
82
+ images = pipe(
83
+ prompt=positive_prompt,
84
+ width=width,
85
+ height=height,
86
+ guidance_scale=guidance_scale,
87
+ num_inference_steps=16,
88
+ num_images_per_prompt=1,
89
+ output_type="pil",
90
+ ).images
91
+ image_paths = [save_image(img) for img in images]
92
+ print(image_paths)
93
+ return image_paths, seed
94
+
95
+
96
+ def load_predefined_images():
97
+ predefined_images = [
98
+ "assets/11.png",
99
+ "assets/22.png",
100
+ "assets/33.png",
101
+ "assets/44.png",
102
+ "assets/55.webp",
103
+ "assets/66.png",
104
+ "assets/77.png",
105
+ "assets/88.png",
106
+ "assets/99.png",
107
+ ]
108
+ return predefined_images
109
+
110
+
111
+
112
+ examples = [
113
+ "A portrait of an attractive woman in her late twenties with light brown hair and purple, wearing large a yellow sweater. She is looking directly at the camera, standing outdoors near trees.. --ar 128:85 --v 6.0 --style raw",
114
+ "A photo of the model wearing a white bodysuit and beige trench coat, posing in front of a train station with hands on head, soft light, sunset, fashion photography, high resolution, 35mm lens, f/22, natural lighting, global illumination. --ar 85:128 --v 6.0 --style raw",
115
+ ]
116
+
117
+
118
+ css = '''
119
+ .gradio-container{max-width: 575px !important}
120
+ h1{text-align:center}
121
+ footer {
122
+ visibility: hidden
123
+ }
124
+ @keyframes snow-fall {
125
+ 0% { top: -10px; }
126
+ 100% { top: 100%; }
127
+ }
128
+
129
+ .snowflake {
130
+ position: fixed;
131
+ top: -10px;
132
+ width: 10px;
133
+ height: 10px;
134
+ background: #00f;
135
+ border-radius: 50%;
136
+ opacity: 0.8;
137
+ pointer-events: none;
138
+ animation: snow-fall linear infinite;
139
+ }
140
+
141
+ .snowfall {
142
+ position: fixed;
143
+ top: 0;
144
+ left: 0;
145
+ width: 100%;
146
+ height: 100%;
147
+ pointer-events: none;
148
+ }
149
+
150
+ '''
151
+
152
+ # Add this JavaScript to generate snowfall effect
153
+ javascript = """
154
+ function createSnowflakes() {
155
+ const snowflakeCount = 50;
156
+ const snowfallContainer = document.createElement('div');
157
+ snowfallContainer.classList.add('snowfall');
158
+ document.body.appendChild(snowfallContainer);
159
+
160
+ for (let i = 0; i < snowflakeCount; i++) {
161
+ const snowflake = document.createElement('div');
162
+ snowflake.classList.add('snowflake');
163
+ snowflake.style.left = `${Math.random() * 100}%`;
164
+ snowflake.style.animationDuration = `${Math.random() * 3 + 2}s`;
165
+ snowflake.style.animationDelay = `${Math.random() * 2}s`;
166
+ snowfallContainer.appendChild(snowflake);
167
+ }
168
+ }
169
+
170
+ document.addEventListener('DOMContentLoaded', createSnowflakes);
171
+ """
172
+
173
+ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
174
+ gr.Markdown(DESCRIPTIONz)
175
+ with gr.Group():
176
+ with gr.Row():
177
+ prompt = gr.Text(
178
+ label="Prompt",
179
+ show_label=False,
180
+ max_lines=1,
181
+ placeholder="Enter your prompt with realism tag!",
182
+ container=False,
183
+ )
184
+ run_button = gr.Button("Run", scale=0)
185
+ result = gr.Gallery(label="Result", columns=1, preview=True, show_label=False)
186
+
187
+ with gr.Accordion("Advanced options", open=False, visible=True):
188
+ seed = gr.Slider(
189
+ label="Seed",
190
+ minimum=0,
191
+ maximum=MAX_SEED,
192
+ step=1,
193
+ value=0,
194
+ visible=True
195
+ )
196
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
197
+
198
+ with gr.Row(visible=True):
199
+ width = gr.Slider(
200
+ label="Width",
201
+ minimum=512,
202
+ maximum=2048,
203
+ step=64,
204
+ value=1024,
205
+ )
206
+ height = gr.Slider(
207
+ label="Height",
208
+ minimum=512,
209
+ maximum=2048,
210
+ step=64,
211
+ value=1024,
212
+ )
213
+
214
+ with gr.Row():
215
+ guidance_scale = gr.Slider(
216
+ label="Guidance Scale",
217
+ minimum=0.1,
218
+ maximum=20.0,
219
+ step=0.1,
220
+ value=3.0,
221
+ )
222
+ num_inference_steps = gr.Slider(
223
+ label="Number of inference steps",
224
+ minimum=1,
225
+ maximum=40,
226
+ step=1,
227
+ value=16,
228
+ )
229
+
230
+ style_selection = gr.Radio(
231
+ show_label=True,
232
+ container=True,
233
+ interactive=True,
234
+ choices=STYLE_NAMES,
235
+ value=DEFAULT_STYLE_NAME,
236
+ label="Quality Style",
237
+ )
238
+
239
+
240
+
241
+ gr.Examples(
242
+ examples=examples,
243
+ inputs=prompt,
244
+ outputs=[result, seed],
245
+ fn=generate,
246
+ cache_examples=False,
247
+ )
248
+
249
+ gr.on(
250
+ triggers=[
251
+ prompt.submit,
252
+ run_button.click,
253
+ ],
254
+ fn=generate,
255
+ inputs=[
256
+ prompt,
257
+ seed,
258
+ width,
259
+ height,
260
+ guidance_scale,
261
+ randomize_seed,
262
+ style_selection,
263
+ ],
264
+ outputs=[result, seed],
265
+ api_name="run",
266
+ )
267
+
268
+ gr.Markdown("### Generated Images")
269
+ predefined_gallery = gr.Gallery(label="Generated Images", columns=3, show_label=False, value=load_predefined_images())
270
+ gr.Markdown("**Disclaimer/Note:**")
271
+
272
+ gr.Markdown("🔥This space provides realistic image generation, which works better for human faces and portraits. Realistic trigger works properly, better for photorealistic trigger words, close-up shots, face diffusion, male, female characters.")
273
+
274
+ gr.Markdown("🔥users are accountable for the content they generate and are responsible for ensuring it meets appropriate ethical standards.")
275
+
276
+ # Include the JavaScript for snowfall effect
277
+ gr.HTML(f"<script>{javascript}</script>")
278
+
279
+ if __name__ == "__main__":
280
  demo.queue(max_size=40).launch()