Oranblock commited on
Commit
d963421
·
verified ·
1 Parent(s): 1f0ed1f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -313
app.py CHANGED
@@ -1,322 +1,41 @@
1
- #!/usr/bin/env python
2
-
3
- import os
4
- import random
5
- import uuid
6
- import json
7
-
8
  import gradio as gr
9
- import numpy as np
10
- from PIL import Image
11
- import spaces
12
  import torch
13
- from diffusers import DiffusionPipeline
14
- from typing import Tuple
15
-
16
- #Check for the Model Base..//
17
-
18
-
19
-
20
- bad_words = json.loads(os.getenv('BAD_WORDS', "[]"))
21
- bad_words_negative = json.loads(os.getenv('BAD_WORDS_NEGATIVE', "[]"))
22
- default_negative = os.getenv("default_negative","")
23
-
24
- def check_text(prompt, negative=""):
25
- for i in bad_words:
26
- if i in prompt:
27
- return True
28
- for i in bad_words_negative:
29
- if i in negative:
30
- return True
31
- return False
32
-
33
-
34
-
35
- style_list = [
36
-
37
- {
38
- "name": "2560 x 1440",
39
- "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic",
40
- "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly",
41
- },
42
-
43
- {
44
- "name": "Photo",
45
- "prompt": "cinematic photo {prompt}. 35mm photograph, film, bokeh, professional, 4k, highly detailed",
46
- "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
47
- },
48
-
49
- {
50
- "name": "Cinematic",
51
- "prompt": "cinematic still {prompt}. emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
52
- "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
53
- },
54
-
55
- {
56
- "name": "Anime",
57
- "prompt": "anime artwork {prompt}. anime style, key visual, vibrant, studio anime, highly detailed",
58
- "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast",
59
- },
60
- {
61
- "name": "3D Model",
62
- "prompt": "professional 3d model {prompt}. octane render, highly detailed, volumetric, dramatic lighting",
63
- "negative_prompt": "ugly, deformed, noisy, low poly, blurry, painting",
64
- },
65
- {
66
- "name": "(No style)",
67
- "prompt": "{prompt}",
68
- "negative_prompt": "",
69
- },
70
- ]
71
-
72
- styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
73
- STYLE_NAMES = list(styles.keys())
74
- DEFAULT_STYLE_NAME = "2560 x 1440"
75
-
76
- def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]:
77
- p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME])
78
- if not negative:
79
- negative = ""
80
- return p.replace("{prompt}", positive), n + negative
81
-
82
-
83
-
84
-
85
-
86
- DESCRIPTION = """## MidJourney
87
-
88
- Hepzeka.com Ücretsiz ve Sınırsız Görsel Üretmek için Yapay Zeka Modeli
89
- """
90
-
91
-
92
-
93
-
94
-
95
- if not torch.cuda.is_available():
96
- DESCRIPTION += "\n<p>⚠️Running on CPU, This may not work on CPU.</p>"
97
-
98
- MAX_SEED = np.iinfo(np.int32).max
99
- CACHE_EXAMPLES = torch.cuda.is_available() and os.getenv("CACHE_EXAMPLES", "0") == "1"
100
- MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "2048"))
101
- USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
102
- ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
103
 
 
104
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
105
 
106
- NUM_IMAGES_PER_PROMPT = 1
107
-
108
  if torch.cuda.is_available():
109
- pipe = DiffusionPipeline.from_pretrained(
110
- "SG161222/RealVisXL_V3.0_Turbo",
111
- torch_dtype=torch.float16,
112
- use_safetensors=True,
113
- add_watermarker=False,
114
- variant="fp16"
115
- )
116
- pipe2 = DiffusionPipeline.from_pretrained(
117
- "SG161222/RealVisXL_V2.02_Turbo",
118
- torch_dtype=torch.float16,
119
- use_safetensors=True,
120
- add_watermarker=False,
121
- variant="fp16"
122
- )
123
- if ENABLE_CPU_OFFLOAD:
124
- pipe.enable_model_cpu_offload()
125
- pipe2.enable_model_cpu_offload()
126
- else:
127
- pipe.to(device)
128
- pipe2.to(device)
129
- print("Loaded on Device!")
130
 
131
- if USE_TORCH_COMPILE:
132
- pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True)
133
- pipe2.unet = torch.compile(pipe2.unet, mode="reduce-overhead", fullgraph=True)
134
- print("Model Compiled!")
135
-
136
- def save_image(img):
137
- unique_name = str(uuid.uuid4()) + ".png"
138
- img.save(unique_name)
139
- return unique_name
140
-
141
- def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
142
- if randomize_seed:
143
- seed = random.randint(0, MAX_SEED)
144
- return seed
145
-
146
- @spaces.GPU(enable_queue=True)
147
- def generate(
148
- prompt: str,
149
- negative_prompt: str = "",
150
- use_negative_prompt: bool = False,
151
- style: str = DEFAULT_STYLE_NAME,
152
- seed: int = 0,
153
- width: int = 1024,
154
- height: int = 1024,
155
- guidance_scale: float = 3,
156
- randomize_seed: bool = False,
157
- use_resolution_binning: bool = True,
158
- progress=gr.Progress(track_tqdm=True),
159
- ):
160
- if check_text(prompt, negative_prompt):
161
- raise ValueError("Prompt contains restricted words.")
162
-
163
- prompt, negative_prompt = apply_style(style, prompt, negative_prompt)
164
- seed = int(randomize_seed_fn(seed, randomize_seed))
165
- generator = torch.Generator().manual_seed(seed)
166
-
167
- if not use_negative_prompt:
168
- negative_prompt = "" # type: ignore
169
- negative_prompt += default_negative
170
-
171
- options = {
172
- "prompt": prompt,
173
- "negative_prompt": negative_prompt,
174
- "width": width,
175
- "height": height,
176
- "guidance_scale": guidance_scale,
177
- "num_inference_steps": 25,
178
- "generator": generator,
179
- "num_images_per_prompt": NUM_IMAGES_PER_PROMPT,
180
- "use_resolution_binning": use_resolution_binning,
181
- "output_type": "pil",
182
- }
183
-
184
- images = pipe(**options).images + pipe2(**options).images
185
-
186
- image_paths = [save_image(img) for img in images]
187
- return image_paths, seed
188
-
189
- examples = [
190
- "Annie Leibovitz tarzında ve Wes Anderson tarzında, rustik bir kabinde, sığ bir alan derinliğine sahip, vintage film grenli, yakın çekim bir kedinin, bir pencerenin yakın çekimi. --ar 85:128 --v 6.0 --stil ham",
191
- "Daria Morgendorffer animasyon serisinin ana karakteri Daria, ciddi ifadesi, çok heyecan verici şehvetli görünümü, çok ateşli bir kız, güzel karizmatik bir kız, çok ateşli bir atış, gözlük takan bir kadın, muhteşem bir figür, ilginç şekiller, gerçek boyutlu figürler",
192
- "Koyu yeşil büyük antoryum yaprakları, yakın çekim, fotoğraf, havadan görünüm, unsplash tarzında, hasselblad h6d400c --ar 85:128 --v 6.0 --style raw",
193
- "Sarışın kadının yakın çekimi alan derinliği, bokeh, sığ odak, minimalizm, Canon EF lensli Fujifilm xh2s, sinematik --ar 85:128 --v 6.0 --style raw"
194
- ]
195
-
196
- css = '''
197
- .gradio-container{max-width: 700px !important}
198
- h1{text-align:center}
199
- '''
200
- with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
201
- gr.Markdown(DESCRIPTION)
202
- gr.DuplicateButton(
203
- value="Duplicate Space for private use",
204
- elem_id="duplicate-button",
205
- visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
206
- )
207
- with gr.Group():
208
- with gr.Row():
209
- prompt = gr.Text(
210
- label="Prompt",
211
- show_label=False,
212
- max_lines=1,
213
- placeholder="Enter your prompt",
214
- container=False,
215
- )
216
- run_button = gr.Button("Run")
217
- result = gr.Gallery(label="Result", columns=1, preview=True)
218
- with gr.Accordion("Advanced options", open=False):
219
- use_negative_prompt = gr.Checkbox(label="Use negative prompt", value=True, visible=True)
220
- negative_prompt = gr.Text(
221
- label="Negative prompt",
222
- max_lines=1,
223
- placeholder="Enter a negative prompt",
224
- value="(deformed iris, deformed pupils, semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime:1.4), text, close up, cropped, out of frame, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck",
225
- visible=True,
226
- )
227
- with gr.Row():
228
- num_inference_steps = gr.Slider(
229
- label="Steps",
230
- minimum=10,
231
- maximum=60,
232
- step=1,
233
- value=30,
234
- )
235
- with gr.Row():
236
- num_images_per_prompt = gr.Slider(
237
- label="Images",
238
- minimum=1,
239
- maximum=5,
240
- step=1,
241
- value=2,
242
- )
243
- seed = gr.Slider(
244
- label="Seed",
245
- minimum=0,
246
- maximum=MAX_SEED,
247
- step=1,
248
- value=0,
249
- visible=True
250
- )
251
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
252
- with gr.Row(visible=True):
253
- width = gr.Slider(
254
- label="Width",
255
- minimum=512,
256
- maximum=2048,
257
- step=8,
258
- value=1024,
259
- )
260
- height = gr.Slider(
261
- label="Height",
262
- minimum=512,
263
- maximum=2048,
264
- step=8,
265
- value=1024,
266
- )
267
- with gr.Row():
268
- guidance_scale = gr.Slider(
269
- label="Guidance Scale",
270
- minimum=0.1,
271
- maximum=20.0,
272
- step=0.1,
273
- value=6,
274
- )
275
- with gr.Row(visible=True):
276
- style_selection = gr.Radio(
277
- show_label=True,
278
- container=True,
279
- interactive=True,
280
- choices=STYLE_NAMES,
281
- value=DEFAULT_STYLE_NAME,
282
- label="Image Style",
283
- )
284
- gr.Examples(
285
- examples=examples,
286
- inputs=prompt,
287
- outputs=[result, seed],
288
- fn=generate,
289
- cache_examples=CACHE_EXAMPLES,
290
- )
291
-
292
- use_negative_prompt.change(
293
- fn=lambda x: gr.update(visible=x),
294
- inputs=use_negative_prompt,
295
- outputs=negative_prompt,
296
- api_name=False,
297
- )
298
-
299
- gr.on(
300
- triggers=[
301
- prompt.submit,
302
- negative_prompt.submit,
303
- run_button.click,
304
- ],
305
- fn=generate,
306
- inputs=[
307
- prompt,
308
- negative_prompt,
309
- use_negative_prompt,
310
- style_selection,
311
- seed,
312
- width,
313
- height,
314
- guidance_scale,
315
- randomize_seed,
316
- ],
317
- outputs=[result, seed],
318
- api_name="run",
319
- )
320
 
321
  if __name__ == "__main__":
322
- demo.queue(max_size=20).launch()
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
2
  import torch
3
+ from diffusers import StableDiffusionPipeline
4
+ import uuid
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ # Check for the Model Base
7
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
8
 
 
 
9
  if torch.cuda.is_available():
10
+ pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", torch_dtype=torch.float16, use_safetensors=True)
11
+ pipe.to(device)
12
+ else:
13
+ pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
14
+
15
+ def generate_stickers(word):
16
+ prompt = (f"Create a set of child-friendly stickers based on the word '{word}'. "
17
+ "Each sticker should have a black bold outline and fit within a label size of 70 x 35 mm, "
18
+ "and be organized into six distinct groups that fit a single A4 sheet with 24 labels per sheet. "
19
+ "Ensure the stickers do not overlap and the black outline is clearly visible. "
20
+ "The stickers should be fun, colorful, and cartoon-like, suitable for children, with a transparent or white background.")
21
+ negative_prompt = ("text, logos, watermarks, out of frame, ugly, extra limbs, bad anatomy, blurry, "
22
+ "overlapping stickers, missing outline")
 
 
 
 
 
 
 
 
23
 
24
+ width, height = 1024, 768 # Appropriate resolution for detailed stickers
25
+ images = pipe(prompt=prompt, negative_prompt=negative_prompt, width=width, height=height, num_inference_steps=50).images
26
+ output_paths = []
27
+ for image in images:
28
+ filename = f"{uuid.uuid4()}.png"
29
+ image.save(filename)
30
+ output_paths.append(filename)
31
+ return output_paths
32
+
33
+ iface = gr.Interface(
34
+ fn=generate_stickers,
35
+ inputs="text",
36
+ outputs="image",
37
+ description="Enter a word to generate a set of child-friendly stickers that fit Sorex A4 Premium Sticker sheets (70x35mm labels per sheet)."
38
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  if __name__ == "__main__":
41
+ iface.launch()