alfredplpl commited on
Commit
4508931
1 Parent(s): e6eab3b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +202 -0
app.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline, EulerAncestralDiscreteScheduler
2
+ from transformers import CLIPFeatureExtractor
3
+ import gradio as gr
4
+ import torch
5
+ from PIL import Image
6
+ import random
7
+
8
+ model_id = 'aipicasso/picasso-diffusion-1-0'
9
+
10
+ scheduler = EulerAncestralDiscreteScheduler.from_pretrained(model_id, subfolder="scheduler")
11
+ feature_extractor = CLIPFeatureExtractor.from_pretrained(model_id)
12
+
13
+ pipe = StableDiffusionPipeline.from_pretrained(
14
+ model_id,
15
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
16
+ scheduler=scheduler)
17
+ pipe.enable_xformers_memory_efficient_attention()
18
+
19
+ pipe_i2i = StableDiffusionImg2ImgPipeline.from_pretrained(
20
+ model_id,
21
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
22
+ scheduler=scheduler,
23
+ requires_safety_checker=False,
24
+ safety_checker=None,
25
+ feature_extractor=feature_extractor
26
+ )
27
+ pipe_i2i.enable_xformers_memory_efficient_attention()
28
+
29
+ if torch.cuda.is_available():
30
+ pipe = pipe.to("cuda")
31
+ pipe_i2i = pipe_i2i.to("cuda")
32
+
33
+ def error_str(error, title="Error"):
34
+ return f"""#### {title}
35
+ {error}""" if error else ""
36
+
37
+
38
+ def inference(prompt, guidance, steps, image_size="Square", seed=0, img=None, strength=0.5, neg_prompt="", cool_japan_type="Anime", disable_auto_prompt_correction=False):
39
+
40
+ generator = torch.Generator('cuda').manual_seed(seed) if seed != 0 else None
41
+
42
+ prompt,neg_prompt=auto_prompt_correction(prompt,neg_prompt,cool_japan_type,disable_auto_prompt_correction)
43
+
44
+ if(image_size=="Portrait"):
45
+ height=1024
46
+ width=768
47
+ elif(image_size=="Landscape"):
48
+ height=768
49
+ width=1024
50
+ elif(image_size=="Highreso."):
51
+ height=1024
52
+ width=1024
53
+ else:
54
+ height=768
55
+ width=768
56
+
57
+ print(prompt,neg_prompt)
58
+
59
+ try:
60
+ if img is not None:
61
+ return img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator), None
62
+ else:
63
+ return txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator), None
64
+ except Exception as e:
65
+ return None, error_str(e)
66
+ def auto_prompt_correction(prompt_ui,neg_prompt_ui,disable_auto_prompt_correction):
67
+ # auto prompt correction
68
+
69
+
70
+ prompt=str(prompt_ui)
71
+ neg_prompt=str(neg_prompt_ui)
72
+ prompt=prompt.lower()
73
+ neg_prompt=neg_prompt.lower()
74
+ if(disable_auto_prompt_correction):
75
+ prompt=f"{cool_japan_type}, {prompt}"
76
+ return prompt, neg_prompt
77
+
78
+ if(prompt=="" and neg_prompt==""):
79
+ prompt="anime, masterpiece, upper body, a girl, good pupil, 4k, detailed"
80
+ neg_prompt=f"(((deformed))), blurry, ((((bad anatomy)))), bad pupil, disfigured, poorly drawn face, mutation, mutated, (extra limb), (ugly), (poorly drawn hands), bad hands, fused fingers, messy drawing, broken legs censor, low quality, (mutated hands and fingers:1.5), (long body :1.3), (mutation, poorly drawn :1.2), ((bad eyes)), ui, error, missing fingers, fused fingers, one hand with more than 5 fingers, one hand with less than 5 fingers, one hand with more than 5 digit, one hand with less than 5 digit, extra digit, fewer digits, fused digit, missing digit, bad digit, liquid digit, long body, uncoordinated body, unnatural body, lowres, jpeg artifacts, 3d, cg, text"
81
+ return prompt, neg_prompt
82
+
83
+ splited_prompt=prompt.replace(","," ").replace("_"," ").split(" ")
84
+ for word in human_words:
85
+ if( word in splited_prompt):
86
+ prompt=f"{cool_japan_type}, masterpiece, {prompt}, good pupil, 4k, detailed"
87
+ neg_prompt=f"(((deformed))), blurry, ((((bad anatomy)))), {neg_prompt}, bad pupil, disfigured, poorly drawn face, mutation, mutated, (extra limb), (ugly), (poorly drawn hands), bad hands, fused fingers, messy drawing, broken legs censor, low quality, (mutated hands and fingers:1.5), (long body :1.3), (mutation, poorly drawn :1.2), ((bad eyes)), ui, error, missing fingers, fused fingers, one hand with more than 5 fingers, one hand with less than 5 fingers, one hand with more than 5 digit, one hand with less than 5 digit, extra digit, fewer digits, fused digit, missing digit, bad digit, liquid digit, long body, uncoordinated body, unnatural body, lowres, jpeg artifacts, 3d, cg, text"
88
+
89
+ animal_words=["cat","dog","bird"]
90
+ for word in animal_words:
91
+ if( word in splited_prompt):
92
+ prompt=f"{cool_japan_type}, a {word}, 4k, detailed"
93
+ neg_prompt=f"(((deformed))), blurry, ((((bad anatomy)))), {neg_prompt}, bad pupil, disfigured, poorly drawn face, mutation, mutated, (extra limb), (ugly), (poorly drawn hands), bad hands, fused fingers, messy drawing, broken legs censor, low quality, (mutated hands and fingers:1.5), (long body :1.3), (mutation, poorly drawn :1.2), ((bad eyes)), ui, error, missing fingers, fused fingers, one hand with more than 5 fingers, one hand with less than 5 fingers, one hand with more than 5 digit, one hand with less than 5 digit, extra digit, fewer digits, fused digit, missing digit, bad digit, liquid digit, long body, uncoordinated body, unnatural body, lowres, jpeg artifacts, 3d, cg, text"
94
+
95
+ background_words=["mount fuji","mt. fuji","building", "buildings", "tokyo", "kyoto", "nara", "shibuya", "shinjuku"]
96
+ for word in background_words:
97
+ if( word in splited_prompt):
98
+ prompt=f"{cool_japan_type}, shinkai makoto, {word}, 4k, 8k, highly detailed"
99
+ neg_prompt=f"(((deformed))), {neg_prompt}, girl, boy, photo, people, low quality, ui, error, lowres, jpeg artifacts, 2d, 3d, cg, text"
100
+
101
+ return prompt,neg_prompt
102
+
103
+ def txt_to_img(prompt, neg_prompt, guidance, steps, width, height, generator):
104
+ result = pipe(
105
+ prompt,
106
+ negative_prompt = neg_prompt,
107
+ num_inference_steps = int(steps),
108
+ guidance_scale = guidance,
109
+ width = width,
110
+ height = height,
111
+ generator = generator)
112
+
113
+ return result.images[0]
114
+
115
+ def img_to_img(prompt, neg_prompt, img, strength, guidance, steps, width, height, generator):
116
+ ratio = min(height / img.height, width / img.width)
117
+ img = img.resize((int(img.width * ratio), int(img.height * ratio)), Image.LANCZOS)
118
+ result = pipe_i2i(
119
+ prompt,
120
+ negative_prompt = neg_prompt,
121
+ init_image = img,
122
+ num_inference_steps = int(steps),
123
+ strength = strength,
124
+ guidance_scale = guidance,
125
+ #width = width,
126
+ #height = height,
127
+ generator = generator)
128
+
129
+ return result.images[0]
130
+
131
+ css = """.main-div div{display:inline-flex;align-items:center;gap:.8rem;font-size:1.75rem}.main-div div h1{font-weight:900;margin-bottom:7px}.main-div p{margin-bottom:10px;font-size:94%}a{text-decoration:underline}.tabs{margin-top:0;margin-bottom:0}#gallery{min-height:20rem}
132
+ """
133
+ with gr.Blocks(css=css) as demo:
134
+ gr.HTML(
135
+ f"""
136
+ <div class="main-div">
137
+ <div>
138
+ <h1>Picasso Diffusion 1.0 Demo</h1>
139
+ </div>
140
+ <p>
141
+ Demo for <a href="https://huggingface.co/aipicasso/picasso-diffusion-1-0">Picasso Diffusion 1.0</a> .<br>
142
+ </p>
143
+ <p>
144
+ サンプル: そのままGenerateボタンを押してください。
145
+ sample : Click "Generate" button without any prompts.
146
+ </p>
147
+ <p>
148
+ sample prompt1 : girl, kimono
149
+ </p>
150
+ <p>
151
+ sample prompt2 : boy, school uniform
152
+ </p>
153
+ Running on {"<b>GPU 🔥</b>" if torch.cuda.is_available() else f"<b>CPU 🥶</b>. For faster inference it is recommended to <b>upgrade to GPU in <a href='https://huggingface.co/spaces/akhaliq/cool-japan-diffusion-2-1-0/settings'>Settings</a></b>"} <br>
154
+ <a style="display:inline-block" href="https://huggingface.co/spaces/aipicasso/cool-japan-diffusion-latest-demo?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a> to say goodbye from waiting for the generating.
155
+ </div>
156
+ """
157
+ )
158
+ with gr.Row():
159
+
160
+ with gr.Column(scale=55):
161
+ with gr.Group():
162
+ with gr.Row():
163
+ cool_japan_type=gr.Radio(["Anime", "Manga", "Game"])
164
+ cool_japan_type.show_label=False
165
+ cool_japan_type.value="Anime"
166
+
167
+ with gr.Row():
168
+ prompt = gr.Textbox(label="Prompt", show_label=False, max_lines=2,placeholder="[your prompt]").style(container=False)
169
+ generate = gr.Button(value="Generate").style(rounded=(False, True, True, False))
170
+
171
+ image_out = gr.Image(height=768,width=768)
172
+ error_output = gr.Markdown()
173
+
174
+ with gr.Column(scale=45):
175
+ with gr.Tab("Options"):
176
+ with gr.Group():
177
+ neg_prompt = gr.Textbox(label="Negative prompt", placeholder="What to exclude from the image")
178
+ disable_auto_prompt_correction = gr.Checkbox(label="Disable auto prompt corretion.")
179
+ with gr.Row():
180
+ image_size=gr.Radio(["Portrait","Landscape","Square","Highreso."])
181
+ image_size.show_label=False
182
+ image_size.value="Square"
183
+
184
+ with gr.Row():
185
+ guidance = gr.Slider(label="Guidance scale", value=7.5, maximum=15)
186
+ steps = gr.Slider(label="Steps", value=20, minimum=2, maximum=75, step=1)
187
+
188
+ seed = gr.Slider(0, 2147483647, label='Seed (0 = random)', value=0, step=1)
189
+
190
+ with gr.Tab("Image to image"):
191
+ with gr.Group():
192
+ image = gr.Image(label="Image", height=256, tool="editor", type="pil")
193
+ strength = gr.Slider(label="Transformation strength", minimum=0, maximum=1, step=0.01, value=0.5)
194
+
195
+ inputs = [prompt, guidance, steps, image_size, seed, image, strength, neg_prompt, cool_japan_type, disable_auto_prompt_correction]
196
+
197
+ outputs = [image_out, error_output]
198
+ prompt.submit(inference, inputs=inputs, outputs=outputs)
199
+ generate.click(inference, inputs=inputs, outputs=outputs,api_name="generate")
200
+
201
+ demo.queue(concurrency_count=1)
202
+ demo.launch()