JarvisLabs commited on
Commit
0d6b248
1 Parent(s): 199ba78

Upload 5 files

Browse files
Files changed (5) hide show
  1. app.py +281 -3
  2. config.py +115 -0
  3. requirements.txt +11 -0
  4. style.css +63 -0
  5. utils.py +193 -0
app.py CHANGED
@@ -1,3 +1,281 @@
1
- import gradio as gr
2
-
3
- gr.load("models/galverse/mama-1.5").launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import gc
4
+ import gradio as gr
5
+ import numpy as np
6
+ import torch
7
+ import json
8
+ import spaces
9
+ import config
10
+
11
+ import logging
12
+ from PIL import Image, PngImagePlugin
13
+ from datetime import datetime
14
+ import replicate
15
+ from config import *
16
+ from utils import *
17
+ IS_COLAB=False
18
+ """
19
+ Changes to base animagine-xl-3.1 log
20
+ - Cut the wildcard
21
+ - add in lora pipeline
22
+ - use let get env variable
23
+ - add in lora strenght variable
24
+
25
+ """
26
+
27
+ logging.basicConfig(level=logging.INFO)
28
+ logger = logging.getLogger(__name__)
29
+
30
+ DESCRIPTION = "Animagine XL 3.1 X Galverse MAMA Replicate Repo "
31
+ IS_COLAB = False
32
+ assert os.environ["REPLICATE_API_TOKEN"], "REPLICATE_API_TOKEN not set "
33
+ MIN_IMAGE_SIZE = 512
34
+ MAX_IMAGE_SIZE = 2048
35
+
36
+ OUTPUT_DIR = os.getenv("OUTPUT_DIR", "./outputs")
37
+
38
+
39
+
40
+ def generate_replicate(
41
+ prompt: str,
42
+ negative_prompt: str = "",
43
+ seed: int = 0,
44
+ custom_width: int = 1024,
45
+ custom_height: int = 1024,
46
+ guidance_scale: float = 7.0,
47
+ num_inference_steps: int = 28,
48
+ sampler: str = "Euler a",
49
+ aspect_ratio_selector: str = "896 x 1152",
50
+ lora_strength: float = 0.7,
51
+ style_selector: str = "(None)",
52
+ quality_selector: str = "Standard v3.1",
53
+ styles: str = "",
54
+ quality_prompt: str = "",
55
+ repo: str="galverse/mama-v1.5.1_leduyson:82d4539e72ec4473d1c34407a378815db55cb2eeb9639b898fcc7b4b67043973",
56
+ lora_id: str= "galverse/mama-1.5",
57
+ lora_style: str = "sks, galverse ",
58
+ progress=gr.Progress(track_tqdm=True),
59
+ ):
60
+ generator = seed_everything(seed)
61
+ width, height = aspect_ratio_handler(
62
+ aspect_ratio_selector,
63
+ custom_width,
64
+ custom_height,
65
+ )
66
+
67
+ # prompt = add_wildcard(prompt, wildcard_files)
68
+ if quality_prompt:
69
+ prompt, negative_prompt = preprocess_prompt(
70
+ quality_prompt, quality_selector, prompt, negative_prompt, add_quality_tags
71
+ )
72
+ if styles:
73
+ prompt, negative_prompt = preprocess_prompt(
74
+ styles, style_selector, prompt, negative_prompt
75
+ )
76
+
77
+ width, height = preprocess_image_dimensions(width, height)
78
+
79
+
80
+ metadata = {
81
+ "prompt": prompt +", " + lora_style,
82
+ "negative_prompt": negative_prompt,
83
+ "resolution": f"{width} x {height}",
84
+ "guidance_scale": guidance_scale,
85
+ "lora_scale":lora_strength,
86
+ "num_inference_steps": num_inference_steps,
87
+ "seed": seed,
88
+ "sampler": sampler,
89
+ "width":width,
90
+ "height":height,
91
+ "num_outputs": 1,
92
+ "guidance_scale":guidance_scale,
93
+ "apply_watermark": True,
94
+ "high_noise_frac": 0.8,
95
+ "disable_safety_checker":True,
96
+ "lora_id": lora_id,
97
+ "seed":seed
98
+ }
99
+ images = replicate.run(
100
+ repo,
101
+ input=metadata
102
+ )
103
+
104
+ image_paths = [
105
+ save_image_replicate(image, metadata, OUTPUT_DIR, IS_COLAB)
106
+ for image in images
107
+ ]
108
+
109
+ for image_path in image_paths:
110
+ logger.info(f"Image saved as {image_path} with metadata")
111
+ return image_paths, metadata
112
+
113
+
114
+ styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
115
+ quality_prompt = {
116
+ k["name"]: (k["prompt"], k["negative_prompt"]) for k in quality_prompt_list
117
+ }
118
+
119
+ with gr.Blocks(css="style.css", theme="NoCrypt/miku@1.2.1") as demo:
120
+ title = gr.HTML(
121
+ f"""<h1><span>{DESCRIPTION}</span></h1>""",
122
+ elem_id="title",
123
+ )
124
+ gr.Markdown(
125
+ f"""Gradio demo for [cagliostrolab/animagine-xl-3.1](https://huggingface.co/cagliostrolab/animagine-xl-3.1)""",
126
+ elem_id="subtitle",
127
+ )
128
+ gr.DuplicateButton(
129
+ value="Duplicate Space for private use",
130
+ elem_id="duplicate-button",
131
+ visible=os.getenv("SHOW_DUPLICATE_BUTTON") == "1",
132
+ )
133
+ with gr.Row():
134
+ with gr.Column(scale=2):
135
+ with gr.Tab("Txt2img"):
136
+ with gr.Group():
137
+ prompt = gr.Text(
138
+ label="Prompt",
139
+ max_lines=5,
140
+ placeholder="Enter your prompt",
141
+ )
142
+ negative_prompt = gr.Text(
143
+ label="Negative Prompt",
144
+ max_lines=5,
145
+ placeholder="Enter a negative prompt",
146
+ )
147
+ lora_strength = gr.Slider(
148
+ label="Lora style strength",
149
+ minimum=0,
150
+ maximum=1,
151
+ step=0.1,
152
+ value=0.7,
153
+ )
154
+ with gr.Accordion(label="Quality Tags", open=True):
155
+ add_quality_tags = gr.Checkbox(
156
+ label="Add Quality Tags", value=True
157
+ )
158
+ quality_selector = gr.Dropdown(
159
+ label="Quality Tags Presets",
160
+ interactive=True,
161
+ choices=list(quality_prompt.keys()),
162
+ value="Standard v3.1",
163
+ )
164
+ with gr.Tab("Advanced Settings"):
165
+ with gr.Group():
166
+ style_selector = gr.Radio(
167
+ label="Style Preset",
168
+ container=True,
169
+ interactive=True,
170
+ choices=list(styles.keys()),
171
+ value="(None)",
172
+ )
173
+ with gr.Group():
174
+ aspect_ratio_selector = gr.Radio(
175
+ label="Aspect Ratio",
176
+ choices=aspect_ratios,
177
+ value="896 x 1152",
178
+ container=True,
179
+ )
180
+ with gr.Group(visible=False) as custom_resolution:
181
+ with gr.Row():
182
+ custom_width = gr.Slider(
183
+ label="Width",
184
+ minimum=MIN_IMAGE_SIZE,
185
+ maximum=MAX_IMAGE_SIZE,
186
+ step=8,
187
+ value=1024,
188
+ )
189
+ custom_height = gr.Slider(
190
+ label="Height",
191
+ minimum=MIN_IMAGE_SIZE,
192
+ maximum=MAX_IMAGE_SIZE,
193
+ step=8,
194
+ value=1024,
195
+ )
196
+
197
+ with gr.Group():
198
+ sampler = gr.Dropdown(
199
+ label="Sampler",
200
+ choices=sampler_list,
201
+ interactive=True,
202
+ value="DPMSolverMultistep",
203
+ )
204
+ with gr.Group():
205
+ seed = gr.Slider(
206
+ label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0
207
+ )
208
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
209
+ with gr.Group():
210
+ with gr.Row():
211
+ guidance_scale = gr.Slider(
212
+ label="Guidance scale",
213
+ minimum=1,
214
+ maximum=12,
215
+ step=0.1,
216
+ value=7.0,
217
+ )
218
+ num_inference_steps = gr.Slider(
219
+ label="Number of inference steps",
220
+ minimum=1,
221
+ maximum=50,
222
+ step=1,
223
+ value=28,
224
+ )
225
+ with gr.Column(scale=3):
226
+ with gr.Blocks():
227
+ run_button = gr.Button("Generate", variant="primary")
228
+ result = gr.Gallery(
229
+ label="Result",
230
+ columns=1,
231
+ height='100%',
232
+ preview=True,
233
+ show_label=False
234
+ )
235
+ with gr.Accordion(label="Generation Parameters", open=False):
236
+ gr_metadata = gr.JSON(label="metadata", show_label=False)
237
+
238
+
239
+ aspect_ratio_selector.change(
240
+ fn=lambda x: gr.update(visible=x == "Custom"),
241
+ inputs=aspect_ratio_selector,
242
+ outputs=custom_resolution,
243
+ queue=False,
244
+ api_name=False,
245
+ )
246
+
247
+ gr.on(
248
+ triggers=[
249
+ prompt.submit,
250
+ negative_prompt.submit,
251
+ run_button.click,
252
+ ],
253
+ fn=randomize_seed_fn,
254
+ inputs=[seed, randomize_seed],
255
+ outputs=seed,
256
+ queue=False,
257
+ api_name=False,
258
+ ).then(
259
+ fn=generate_replicate,
260
+ inputs=[
261
+ prompt,
262
+ negative_prompt,
263
+ seed,
264
+ custom_width,
265
+ custom_height,
266
+ guidance_scale,
267
+ num_inference_steps,
268
+ sampler,
269
+ aspect_ratio_selector,
270
+ lora_strength,
271
+ style_selector,
272
+ quality_selector,
273
+ quality_prompt,
274
+
275
+ ],
276
+ outputs=[result, gr_metadata],
277
+ api_name="run",
278
+ )
279
+
280
+ if __name__ == "__main__":
281
+ demo.queue(max_size=20).launch(debug=IS_COLAB, share=IS_COLAB)
config.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ examples = [
2
+ "1girl, souryuu asuka langley, neon genesis evangelion, plugsuit, pilot suit, red bodysuit, sitting, crossing legs, black eye patch, cat hat, throne, symmetrical, looking down, from bottom, looking at viewer, outdoors",
3
+ "1boy, male focus, yuuki makoto \(persona 3\), persona 3, black jacket, white shirt, long sleeves, closed mouth, glowing eyes, gun, hair over one eye, holding gun, handgun, looking at viewer, solo, upper body",
4
+ "1girl, makima \(chainsaw man\), chainsaw man, black jacket, black necktie, black pants, braid, business suit, fingernails, formal, hand on own chin, jacket on shoulders, light smile, long sleeves, looking at viewer, looking up, medium breasts, office lady, smile, solo, suit, upper body, white shirt, outdoors",
5
+ "1boy, male focus, gojou satoru, jujutsu kaisen, black jacket, blindfold lift, blue eyes, glowing, glowing eyes, high collar, jacket, jujutsu tech uniform, solo, grin, white hair",
6
+ "1girl, cagliostro, granblue fantasy, violet eyes, standing, hand on own chin, looking at object, smile, closed mouth, table, beaker, glass tube, experiment apparatus, dark room, laboratory",
7
+ "kimi no na wa., building, cityscape, cloud, cloudy sky, gradient sky, lens flare, no humans, outdoors, power lines, scenery, shooting star, sky, sparkle, star \(sky\), starry sky, sunset, tree, utility pole",
8
+ ]
9
+
10
+ quality_prompt_list = [
11
+ {
12
+ "name": "(None)",
13
+ "prompt": "{prompt}",
14
+ "negative_prompt": "nsfw, lowres",
15
+ },
16
+ {
17
+ "name": "Standard v3.0",
18
+ "prompt": "{prompt}, masterpiece, best quality",
19
+ "negative_prompt": "nsfw, lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, artist name",
20
+ },
21
+ {
22
+ "name": "Standard v3.1",
23
+ "prompt": "{prompt}, masterpiece, best quality, very aesthetic, absurdres",
24
+ "negative_prompt": "nsfw, lowres, (bad), text, error, fewer, extra, missing, worst quality, jpeg artifacts, low quality, watermark, unfinished, displeasing, oldest, early, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract]",
25
+ },
26
+ {
27
+ "name": "Light v3.1",
28
+ "prompt": "{prompt}, (masterpiece), best quality, very aesthetic, perfect face",
29
+ "negative_prompt": "nsfw, (low quality, worst quality:1.2), very displeasing, 3d, watermark, signature, ugly, poorly drawn",
30
+ },
31
+ {
32
+ "name": "Heavy v3.1",
33
+ "prompt": "{prompt}, (masterpiece), (best quality), (ultra-detailed), very aesthetic, illustration, disheveled hair, perfect composition, moist skin, intricate details",
34
+ "negative_prompt": "nsfw, longbody, lowres, bad anatomy, bad hands, missing fingers, pubic hair, extra digit, fewer digits, cropped, worst quality, low quality, very displeasing",
35
+ },
36
+ ]
37
+
38
+ sampler_list = [
39
+ "DDIM",
40
+ "DPMSolverMultistep",
41
+ "DPMPP_2M_SDE",
42
+ "DPMPP_2M_SDE_KARRAS",
43
+ "DPMPP_2M_KARRAS",
44
+ "HeunDiscrete",
45
+ "KarrasDPM",
46
+ "K_EULER_ANCESTRAL",
47
+ "K_EULER",
48
+ "PNDM",
49
+ ]
50
+
51
+ aspect_ratios = [
52
+ "1024 x 1024",
53
+ "1152 x 896",
54
+ "896 x 1152",
55
+ "1216 x 832",
56
+ "832 x 1216",
57
+ "1344 x 768",
58
+ "768 x 1344",
59
+ "1536 x 640",
60
+ "640 x 1536",
61
+ "Custom",
62
+ ]
63
+
64
+ style_list = [
65
+ {
66
+ "name": "(None)",
67
+ "prompt": "{prompt}",
68
+ "negative_prompt": "",
69
+ },
70
+ {
71
+ "name": "Cinematic",
72
+ "prompt": "{prompt}, cinematic still, emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy",
73
+ "negative_prompt": "nsfw, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured",
74
+ },
75
+ {
76
+ "name": "Photographic",
77
+ "prompt": "{prompt}, cinematic photo, 35mm photograph, film, bokeh, professional, 4k, highly detailed",
78
+ "negative_prompt": "nsfw, drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly",
79
+ },
80
+ {
81
+ "name": "Anime",
82
+ "prompt": "{prompt}, anime artwork, anime style, key visual, vibrant, studio anime, highly detailed",
83
+ "negative_prompt": "nsfw, photo, deformed, black and white, realism, disfigured, low contrast",
84
+ },
85
+ {
86
+ "name": "Manga",
87
+ "prompt": "{prompt}, manga style, vibrant, high-energy, detailed, iconic, Japanese comic style",
88
+ "negative_prompt": "nsfw, ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, Western comic style",
89
+ },
90
+ {
91
+ "name": "Digital Art",
92
+ "prompt": "{prompt}, concept art, digital artwork, illustrative, painterly, matte painting, highly detailed",
93
+ "negative_prompt": "nsfw, photo, photorealistic, realism, ugly",
94
+ },
95
+ {
96
+ "name": "Pixel art",
97
+ "prompt": "{prompt}, pixel-art, low-res, blocky, pixel art style, 8-bit graphics",
98
+ "negative_prompt": "nsfw, sloppy, messy, blurry, noisy, highly detailed, ultra textured, photo, realistic",
99
+ },
100
+ {
101
+ "name": "Fantasy art",
102
+ "prompt": "{prompt}, ethereal fantasy concept art, magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy",
103
+ "negative_prompt": "nsfw, photographic, realistic, realism, 35mm film, dslr, cropped, frame, text, deformed, glitch, noise, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, sloppy, duplicate, mutated, black and white",
104
+ },
105
+ {
106
+ "name": "Neonpunk",
107
+ "prompt": "{prompt}, neonpunk style, cyberpunk, vaporwave, neon, vibes, vibrant, stunningly beautiful, crisp, detailed, sleek, ultramodern, magenta highlights, dark purple shadows, high contrast, cinematic, ultra detailed, intricate, professional",
108
+ "negative_prompt": "nsfw, painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured",
109
+ },
110
+ {
111
+ "name": "3D Model",
112
+ "prompt": "{prompt}, professional 3d model, octane render, highly detailed, volumetric, dramatic lighting",
113
+ "negative_prompt": "nsfw, ugly, deformed, noisy, low poly, blurry, painting",
114
+ },
115
+ ]
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.27.2
2
+ diffusers==0.26.3
3
+ gradio==4.20.0
4
+ invisible-watermark==0.2.0
5
+ Pillow==10.2.0
6
+ spaces==0.24.0
7
+ torch==2.0.1
8
+ transformers==4.38.1
9
+ omegaconf==2.3.0
10
+ timm==0.9.10
11
+ replicate
style.css ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --title-font-size: clamp(1.5rem, 6vw, 3rem);
3
+ --subtitle-font-size: clamp(1rem, 2vw, 1.2rem);
4
+ }
5
+
6
+ h1 {
7
+ text-align: center;
8
+ font-size: var(--title-font-size);
9
+ display: block;
10
+ }
11
+
12
+ h2 {
13
+ text-align: center;
14
+ font-size: 2rem;
15
+ display: block;
16
+ }
17
+
18
+ #duplicate-button {
19
+ display: block;
20
+ margin: 1rem auto;
21
+ color: #fff;
22
+ background: #800eb1;
23
+ border-radius: 100vh;
24
+ padding: 0.5rem 1rem;
25
+ }
26
+
27
+ #component-0 {
28
+ max-width: 85%;
29
+ margin: 2rem auto;
30
+ padding: 2rem;
31
+ }
32
+
33
+ @media (max-width: 600px) {
34
+ #component-0 {
35
+ max-width: 100%;
36
+ padding: 0.5rem;
37
+ }
38
+ }
39
+
40
+ #title-container {
41
+ text-align: center;
42
+ padding: 2rem 0;
43
+ }
44
+
45
+ #title {
46
+ font-size: var(--title-font-size);
47
+ color: #333;
48
+ font-family: 'Helvetica Neue', sans-serif;
49
+ text-transform: uppercase;
50
+ background: transparent;
51
+ }
52
+
53
+ #title span {
54
+ background: linear-gradient(45deg, #f30abd, #28b485);
55
+ background-clip: text;
56
+ color: transparent;
57
+ }
58
+
59
+ #subtitle {
60
+ text-align: center;
61
+ font-size: var(--subtitle-font-size);
62
+ margin-top: 1rem;
63
+ }
utils.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gc
2
+ import os
3
+ import random
4
+ import numpy as np
5
+ import json
6
+ import torch
7
+ import uuid
8
+ from PIL import Image, PngImagePlugin
9
+ from datetime import datetime
10
+ from dataclasses import dataclass
11
+ from typing import Callable, Dict, Optional, Tuple
12
+ from diffusers import (
13
+ DDIMScheduler,
14
+ DPMSolverMultistepScheduler,
15
+ DPMSolverSinglestepScheduler,
16
+ EulerAncestralDiscreteScheduler,
17
+ EulerDiscreteScheduler,
18
+ )
19
+
20
+ MAX_SEED = np.iinfo(np.int32).max
21
+
22
+
23
+ @dataclass
24
+ class StyleConfig:
25
+ prompt: str
26
+ negative_prompt: str
27
+
28
+
29
+ def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
30
+ if randomize_seed:
31
+ seed = random.randint(0, MAX_SEED)
32
+ return seed
33
+
34
+
35
+ def seed_everything(seed: int) -> torch.Generator:
36
+ torch.manual_seed(seed)
37
+ torch.cuda.manual_seed_all(seed)
38
+ np.random.seed(seed)
39
+ generator = torch.Generator()
40
+ generator.manual_seed(seed)
41
+ return generator
42
+
43
+
44
+ def parse_aspect_ratio(aspect_ratio: str) -> Optional[Tuple[int, int]]:
45
+ if aspect_ratio == "Custom":
46
+ return None
47
+ width, height = aspect_ratio.split(" x ")
48
+ return int(width), int(height)
49
+
50
+
51
+ def aspect_ratio_handler(
52
+ aspect_ratio: str, custom_width: int, custom_height: int
53
+ ) -> Tuple[int, int]:
54
+ if aspect_ratio == "Custom":
55
+ return custom_width, custom_height
56
+ else:
57
+ width, height = parse_aspect_ratio(aspect_ratio)
58
+ return width, height
59
+
60
+
61
+ def get_scheduler(scheduler_config: Dict, name: str) -> Optional[Callable]:
62
+ scheduler_factory_map = {
63
+ "DPM++ 2M Karras": lambda: DPMSolverMultistepScheduler.from_config(
64
+ scheduler_config, use_karras_sigmas=True
65
+ ),
66
+ "DPM++ SDE Karras": lambda: DPMSolverSinglestepScheduler.from_config(
67
+ scheduler_config, use_karras_sigmas=True
68
+ ),
69
+ "DPM++ 2M SDE Karras": lambda: DPMSolverMultistepScheduler.from_config(
70
+ scheduler_config, use_karras_sigmas=True, algorithm_type="sde-dpmsolver++"
71
+ ),
72
+ "Euler": lambda: EulerDiscreteScheduler.from_config(scheduler_config),
73
+ "Euler a": lambda: EulerAncestralDiscreteScheduler.from_config(
74
+ scheduler_config
75
+ ),
76
+ "DDIM": lambda: DDIMScheduler.from_config(scheduler_config),
77
+ }
78
+ return scheduler_factory_map.get(name, lambda: None)()
79
+
80
+
81
+ def free_memory() -> None:
82
+ torch.cuda.empty_cache()
83
+ gc.collect()
84
+
85
+
86
+ def preprocess_prompt(
87
+ style_dict,
88
+ style_name: str,
89
+ positive: str,
90
+ negative: str = "",
91
+ add_style: bool = True,
92
+ ) -> Tuple[str, str]:
93
+ p, n = style_dict.get(style_name, style_dict["(None)"])
94
+
95
+ if add_style and positive.strip():
96
+ formatted_positive = p.format(prompt=positive)
97
+ else:
98
+ formatted_positive = positive
99
+
100
+ combined_negative = n
101
+ if negative.strip():
102
+ if combined_negative:
103
+ combined_negative += ", " + negative
104
+ else:
105
+ combined_negative = negative
106
+
107
+ return formatted_positive, combined_negative
108
+
109
+
110
+ def common_upscale(
111
+ samples: torch.Tensor,
112
+ width: int,
113
+ height: int,
114
+ upscale_method: str,
115
+ ) -> torch.Tensor:
116
+ return torch.nn.functional.interpolate(
117
+ samples, size=(height, width), mode=upscale_method
118
+ )
119
+
120
+
121
+ def upscale(
122
+ samples: torch.Tensor, upscale_method: str, scale_by: float
123
+ ) -> torch.Tensor:
124
+ width = round(samples.shape[3] * scale_by)
125
+ height = round(samples.shape[2] * scale_by)
126
+ return common_upscale(samples, width, height, upscale_method)
127
+
128
+
129
+
130
+ def get_random_line_from_file(file_path: str) -> str:
131
+ with open(file_path, "r") as file:
132
+ lines = file.readlines()
133
+ if not lines:
134
+ return ""
135
+ return random.choice(lines).strip()
136
+
137
+ def preprocess_image_dimensions(width, height):
138
+ if width % 8 != 0:
139
+ width = width - (width % 8)
140
+ if height % 8 != 0:
141
+ height = height - (height % 8)
142
+ return width, height
143
+
144
+ from PIL import Image
145
+ import requests
146
+ from io import BytesIO
147
+ def save_image_replicate(image_url, metadata, output_dir, is_colab):
148
+ """
149
+ Saves an image from a given URL to the specified output directory with metadata.
150
+
151
+ Args:
152
+ image_url (str): The URL of the image to be saved.
153
+ metadata (dict): A dictionary containing metadata about the image.
154
+ output_dir (str): The directory where the image will be saved.
155
+ is_colab (bool): A flag indicating whether the function is running in a Google Colab environment.
156
+
157
+ Returns:
158
+ str: The filepath of the saved image.
159
+ """
160
+ current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
161
+ filename = f"image_{current_time}.png"
162
+ else:
163
+ filename = str(uuid.uuid4()) + ".png"
164
+ os.makedirs(output_dir, exist_ok=True)
165
+ response = requests.get(image_url)
166
+ image = Image.open(BytesIO(response.content))
167
+ filepath = os.path.join(output_dir, filename)
168
+ metadata_str = json.dumps(metadata)
169
+ info = PngImagePlugin.PngInfo()
170
+ info.add_text("metadata", metadata_str)
171
+ image.save(filepath, "PNG", pnginfo=info)
172
+ return filepath
173
+
174
+ def save_image(image, metadata, output_dir, is_colab):
175
+ if is_colab:
176
+ current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
177
+ filename = f"image_{current_time}.png"
178
+ else:
179
+ filename = str(uuid.uuid4()) + ".png"
180
+ os.makedirs(output_dir, exist_ok=True)
181
+ filepath = os.path.join(output_dir, filename)
182
+ metadata_str = json.dumps(metadata)
183
+ info = PngImagePlugin.PngInfo()
184
+ info.add_text("metadata", metadata_str)
185
+ image.save(filepath, "PNG", pnginfo=info)
186
+ return filepath
187
+
188
+
189
+ def is_google_colab():
190
+ try:
191
+ import google.colab
192
+ return True
193
+ except: