shellypeng commited on
Commit
458e83a
·
verified ·
1 Parent(s): 9ce1e2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +340 -9
app.py CHANGED
@@ -1,12 +1,343 @@
1
- from huggingface_hub import Repository
 
2
 
3
- repo = Repository(
4
- local_dir="anime_pack_app_py",
5
- repo_type="model",
6
- clone_from="shellypeng/anime_pack_app_py",
7
- token=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  )
9
- repo.git_pull()
10
 
11
- from anime_pack_app_py import model
12
- model.run()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Test_gradio_push.ipynb
3
 
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1mlZpAq-EWRmmLHH4Ok533awreqtJwzzW
8
+ """
9
+
10
+ """# HF Script
11
+
12
+ """
13
+
14
+ # -*- coding: utf-8 -*-
15
+ """Copy of Anime_Pack_Gradio.ipynb
16
+
17
+ Automatically generated by Colaboratory.
18
+
19
+ Original file is located at
20
+ https://colab.research.google.com/drive/1RxVCwOkq3Q5qlEkQxhFGeUxICBujjEjR
21
+ """
22
+
23
+ import os
24
+
25
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
26
+
27
+ tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-zh-en")
28
+
29
+ model = AutoModelForSeq2SeqLM.from_pretrained("Helsinki-NLP/opus-mt-zh-en")
30
+
31
+ import gradio as gr
32
+ import numpy as np
33
+ from PIL import Image
34
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, DPMSolverMultistepScheduler, StableDiffusionImg2ImgPipeline
35
+
36
+ import torch
37
+ from controlnet_aux import HEDdetector
38
+ from diffusers.utils import load_image
39
+
40
+ import concurrent.futures
41
+ from threading import Thread
42
+ from compel import Compel
43
+
44
+
45
+ from transformers import pipeline
46
+
47
+
48
+ model_ckpt = "papluca/xlm-roberta-base-language-detection"
49
+ pipe = pipeline("text-classification", model=model_ckpt)
50
+
51
+ HF_TOKEN = os.environ.get("HUGGING_FACE_HUB_TOKEN")
52
+
53
+ device="cuda" if torch.cuda.is_available() else "cpu"
54
+
55
+ hidden_booster_text = "masterpiece++, best quality++, ultra-detailed+ +, unity 8k wallpaper+, illustration+, anime style+, intricate, fluid simulation, sharp edges. glossy++, Smooth++, detailed eyes++, best quality++,4k++,8k++,highres++,masterpiece++,ultra- detailed,realistic++,photorealistic++,photo-realistic++,depth of field, ultra-high definition, highly detailed, natural lighting, sharp focus, cinematic, hyperrealism,extremely detailed"
56
+ hidden_negative = "bad anatomy, disfigured, poorly drawn,deformed, mutation, malformation, deformed, mutated, disfigured, deformed eyes+, bad face++, bad hands, poorly drawn hands, malformed hands, extra arms++, extra legs++, Fused body+, Fused hands+, Fused legs+, missing arms, missing limb, extra digit+, fewer digits, floating limbs, disconnected limbs, inaccurate limb, bad fingers, missing fingers, ugly face, long body++"
57
+ hidden_cn_booster_text = ",漂亮的脸"
58
+ hidden_cn_negative = ""
59
+
60
+ def translate(prompt):
61
+ trans_text = prompt
62
+ translated = model.generate(**tokenizer(trans_text, return_tensors="pt", padding=True))
63
+ tgt_text = [tokenizer.decode(t, skip_special_tokens=True) for t in translated]
64
+ tgt_text = ''.join(tgt_text)[:-1]
65
+ return tgt_text
66
+
67
+
68
+ hed = HEDdetector.from_pretrained('lllyasviel/ControlNet')
69
+
70
+ controlnet_scribble = ControlNetModel.from_pretrained(
71
+ "lllyasviel/sd-controlnet-scribble", torch_dtype=torch.float16, safety_checker=None, requires_safety_checker=False, )
72
+
73
+ pipe_scribble = StableDiffusionControlNetPipeline.from_single_file(
74
+ "https://huggingface.co/shellypeng/anime-god/blob/main/animeGod_v10.safetensors", controlnet=controlnet_scribble, safety_checker=None, requires_safety_checker=False,
75
+ torch_dtype=torch.float16, token=HF_TOKEN
76
+ )
77
+
78
+ pipe_scribble.load_lora_weights("shellypeng/lora2")
79
+ pipe_scribble.fuse_lora(lora_scale=0.1)
80
+
81
+ pipe_scribble.load_textual_inversion("shellypeng/textinv1")
82
+ pipe_scribble.load_textual_inversion("shellypeng/textinv2")
83
+ pipe_scribble.load_textual_inversion("shellypeng/textinv3")
84
+ pipe_scribble.load_textual_inversion("shellypeng/textinv4")
85
+ pipe_scribble.scheduler = DPMSolverMultistepScheduler.from_config(pipe_scribble.scheduler.config, use_karras_sigmas=True)
86
+ pipe_scribble.safety_checker = None
87
+ pipe_scribble.requires_safety_checker = False
88
+ pipe_scribble.to(device)
89
+ pipe_scribble.safety_checker = lambda images, **kwargs: (images, [False] * len(images))
90
+
91
+
92
+ def scribble_to_image(text, neg_prompt_box, input_img):
93
+ """
94
+ pass the sd model and do scribble to image
95
+ include Adetailer, detail tweaker lora, prompt backend include: beautiful eyes, beautiful face, beautiful hand, (maybe infer from user's prompt for gesture and facial
96
+ expression to improve hand)
97
+ """
98
+
99
+
100
+
101
+ # if auto detect detects chinese => auto turn on chinese prompting checkbox
102
+ # change param "bag" below to text, image param below to input_img
103
+ input_img = Image.fromarray(input_img)
104
+ input_img = hed(input_img, scribble=True)
105
+ input_img = load_image(input_img)
106
+ # global prompt
107
+ lang_check_label = pipe(text, top_k=1, truncation=True)[0]['label']
108
+ lang_check_score = pipe(text, top_k=1, truncation=True)[0]['score']
109
+ if lang_check_label == 'zh' and lang_check_score >= 0.85:
110
+ text = translate(text)
111
+ compel_proc = Compel(tokenizer=pipe_scribble.tokenizer, text_encoder=pipe_scribble.text_encoder)
112
+ prompt = text + hidden_booster_text
113
+ prompt_embeds = compel_proc(prompt)
114
+ negative_prompt = neg_prompt_box + hidden_negative
115
+ negative_prompt_embeds = compel_proc(negative_prompt)
116
+
117
+ res_image0 = pipe_scribble(image=input_img, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, num_inference_steps=40).images[0]
118
+ res_image1 = pipe_scribble(image=input_img, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, num_inference_steps=40).images[0]
119
+ res_image2 = pipe_scribble(image=input_img, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, num_inference_steps=40).images[0]
120
+ res_image3 = pipe_scribble(image=input_img, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, num_inference_steps=40).images[0]
121
+
122
+ return res_image0, res_image1, res_image2, res_image3
123
+
124
+ def real_img2img_to_anime(text, neg_prompt_box, input_img):
125
+ """
126
+ pass the sd model and do scribble to image
127
+ include Adetailer, detail tweaker lora, prompt backend include: beautiful eyes, beautiful face, beautiful hand, (maybe infer from user's prompt for gesture and facial
128
+ expression to improve hand)
129
+ """
130
+ input_img = Image.fromarray(input_img)
131
+ input_img = load_image(input_img)
132
+ lang_check_label = pipe(text, top_k=1, truncation=True)[0]['label']
133
+ lang_check_score = pipe(text, top_k=1, truncation=True)[0]['score']
134
+ if lang_check_label == 'zh' and lang_check_score >= 0.85:
135
+ text = translate(text)
136
+
137
+ compel_proc = Compel(tokenizer=pipe_scribble.tokenizer, text_encoder=pipe_scribble.text_encoder)
138
+ prompt = text + hidden_booster_text
139
+ prompt_embeds = compel_proc(prompt)
140
+
141
+ negative_prompt = neg_prompt_box + hidden_negative
142
+ negative_prompt_embeds = compel_proc(negative_prompt)
143
+ # input_img = depth_estimator(input_img)['depth']
144
+ res_image0 = pipe_img2img(image=input_img, strength=0.6, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, num_inference_steps=40).images[0]
145
+ res_image1 = pipe_img2img(image=input_img, strength=0.6, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, num_inference_steps=40).images[0]
146
+ res_image2 = pipe_img2img(image=input_img, strength=0.6, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, num_inference_steps=40).images[0]
147
+ res_image3 = pipe_img2img(image=input_img, strength=0.6, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, num_inference_steps=40).images[0]
148
+
149
+ return res_image0, res_image1, res_image2, res_image3
150
+
151
+
152
+ theme = gr.themes.Soft(
153
+ primary_hue="orange",
154
+ secondary_hue="orange",
155
+ ).set(
156
+ block_background_fill='*primary_50'
157
  )
 
158
 
159
+
160
+ pipe_img2img = StableDiffusionImg2ImgPipeline.from_single_file("https://huggingface.co/shellypeng/anime-god/blob/main/animeGod_v10.safetensors",
161
+ torch_dtype=torch.float16, safety_checker=None, requires_safety_checker=False, token=HF_TOKEN)
162
+
163
+ pipe_img2img.load_lora_weights("shellypeng/lora1")
164
+ pipe_img2img.fuse_lora(lora_scale=0.1)
165
+ pipe_img2img.load_lora_weights("shellypeng/lora2", token=HF_TOKEN)
166
+ pipe_img2img.fuse_lora(lora_scale=0.1)
167
+
168
+ pipe_img2img.load_textual_inversion("shellypeng/textinv1")
169
+ pipe_img2img.load_textual_inversion("shellypeng/textinv2")
170
+ pipe_img2img.load_textual_inversion("shellypeng/textinv3")
171
+ pipe_img2img.load_textual_inversion("shellypeng/textinv4")
172
+ pipe_img2img.scheduler = DPMSolverMultistepScheduler.from_config(pipe_img2img.scheduler.config, use_karras_sigmas=True)
173
+ pipe_img2img.safety_checker = None
174
+ pipe_img2img.requires_safety_checker = False
175
+ pipe_img2img.to(device)
176
+
177
+ pipe_img2img.safety_checker = lambda images, **kwargs: (images, [False] * len(images))
178
+
179
+ def zh_prompt_info(text, neg_text, chinese_check):
180
+ can_raise_info = ""
181
+ lang_check_label = pipe(text, top_k=1, truncation=True)[0]['label']
182
+ lang_check_score = pipe(text, top_k=1, truncation=True)[0]['score']
183
+ neg_lang_check_label = pipe(neg_text, top_k=1, truncation=True)[0]['label']
184
+ neg_lang_check_score = pipe(neg_text, top_k=1, truncation=True)[0]['score']
185
+ print(lang_check_label)
186
+ if lang_check_label == 'zh' and lang_check_score >= 0.85:
187
+ if not chinese_check:
188
+ chinese_check = True
189
+ can_raise_info = "zh"
190
+ if neg_lang_check_label == 'en' and neg_lang_check_score >= 0.85:
191
+ can_raise_info = "invalid"
192
+ return True, can_raise_info
193
+ elif lang_check_label == 'en' and lang_check_score >= 0.85:
194
+ if chinese_check:
195
+ chinese_check = False
196
+ can_raise_info = "en"
197
+ if neg_lang_check_label == 'zh' and neg_lang_check_score >= 0.85:
198
+ can_raise_info = "invalid"
199
+ return False, can_raise_info
200
+ return chinese_check, can_raise_info
201
+ def mult_thread_img2img(prompt_box, neg_prompt_box, image_box):
202
+ with concurrent.futures.ThreadPoolExecutor(max_workers=12000) as executor:
203
+ future = executor.submit(real_img2img_to_anime, prompt_box, neg_prompt_box, image_box)
204
+ image1, image2, image3, image4 = future.result()
205
+ return image1, image2, image3, image4
206
+ def mult_thread_scribble(prompt_box, neg_prompt_box, image_box):
207
+ with concurrent.futures.ThreadPoolExecutor(max_workers=12000) as executor:
208
+ future = executor.submit(scribble_to_image, prompt_box, neg_prompt_box, image_box)
209
+ image1, image2, image3, image4 = future.result()
210
+ return image1, image2, image3, image4
211
+ def mult_thread_live_scribble(prompt_box, neg_prompt_box, image_box):
212
+ image_box = image_box["composite"]
213
+ with concurrent.futures.ThreadPoolExecutor(max_workers=12000) as executor:
214
+ future = executor.submit(scribble_to_image, prompt_box, neg_prompt_box, image_box)
215
+ image1, image2, image3, image4 = future.result()
216
+ return image1, image2, image3, image4
217
+ def mult_thread_lang_class(prompt_box, neg_prompt_box, chinese_check):
218
+
219
+ with concurrent.futures.ThreadPoolExecutor(max_workers=12000) as executor:
220
+ future = executor.submit(zh_prompt_info, prompt_box, neg_prompt_box, chinese_check)
221
+ chinese_check, can_raise_info = future.result()
222
+ if can_raise_info == "zh":
223
+ gr.Info("Chinese Language Detected, Switching to Chinese Prompt Mode")
224
+ elif can_raise_info == "en":
225
+ gr.Info("English Language Detected, Disabling Chinese Prompt Mode")
226
+ return chinese_check
227
+
228
+
229
+ with gr.Blocks(theme=theme, css="footer {visibility: hidden}", title="ShellAI Apps") as iface:
230
+ with gr.Tab("Animefier(安妮漫风)"):
231
+ gr.Markdown(
232
+ """
233
+ # Animefier(安妮漫风)
234
+ Turns realistic photos into one in the anime style.
235
+ 将真实图片转为动漫风图片。
236
+ """
237
+ )
238
+ with gr.Row(equal_height=True):
239
+ with gr.Column():
240
+ with gr.Row(equal_height=True):
241
+ with gr.Column(scale=4):
242
+ prompt_box = gr.Textbox(label="Prompt(提示词)", placeholder="Enter a prompt\n输入提示词", lines=3)
243
+ neg_prompt_box = gr.Textbox(label="Negative Prompt(负面提示词)", placeholder="Enter a negative prompt(things you don't want to include in the generated image)\n输入负面提示词:输入您不想生成的部分", lines=3)
244
+ with gr.Row(equal_height=True):
245
+ chinese_check = gr.Checkbox(label="Chinese Prompt Mode(中文提示词模式)", info="Click here to enable Chinese Prompting(点此触发中文提示词输入)")
246
+
247
+ image_box = gr.Image(label="Input Image(上传图片)", height=400)
248
+ gen_btn = gr.Button(value="Generate(生成)")
249
+
250
+ with gr.Row(equal_height=True):
251
+ image1 = gr.Image(label="Result 1(结果图 1)")
252
+ image2 = gr.Image(label="Result 2(结果图 2)")
253
+ image3 = gr.Image(label="Result 3(结果图 3)")
254
+ image4 = gr.Image(label="Result 4(结果图 4)")
255
+ example_img2img = [
256
+ ["漂亮的女孩,微笑,长发,黑发,粉色外套,白色内衬,优雅,红色背景,红色窗帘", "低画质", "sunmi.jpg"],
257
+ ["Beautiful girl, smiling, bun, bun hair, black hair, beautiful eyes, black dress, elegant, red carpet photo","ugly, bad quality", "emma.jpg"]
258
+ ]
259
+
260
+ gr.Examples(examples=example_img2img, inputs=[prompt_box, neg_prompt_box, image_box], outputs=[image1, image2, image3, image4], fn=mult_thread_img2img, cache_examples=True)
261
+
262
+ gr.on(triggers=[prompt_box.submit, gen_btn.click],fn=mult_thread_lang_class, inputs=[prompt_box, neg_prompt_box, chinese_check], outputs=[chinese_check], show_progress=False)
263
+ gr.on(triggers=[prompt_box.submit, gen_btn.click],fn=mult_thread_img2img, inputs=[prompt_box, neg_prompt_box, image_box], outputs=[image1, image2, image3, image4])
264
+ with gr.Tab("Live Sketch(实时涂鸦)"):
265
+ gr.Markdown(
266
+ """
267
+ # Live Sketch(实时涂鸦)
268
+ Live draw sketches/scribbles and turns into one in the anime style.
269
+ 实时涂鸦,将粗线条涂鸦转为动漫风图片。
270
+ """
271
+ )
272
+ with gr.Row(equal_height=True):
273
+ with gr.Column():
274
+ with gr.Row(equal_height=True):
275
+ with gr.Column(scale=4):
276
+ prompt_box = gr.Textbox(label="Prompt(提示词)", placeholder="Enter a prompt\n输入提示词", lines=3)
277
+ neg_prompt_box = gr.Textbox(label="Negative Prompt(负面提示词)", placeholder="Enter a negative prompt(things you don't want to include in the generated image)\n输入负面提示词:输入您不想生成的部分", lines=3)
278
+ with gr.Row(equal_height=True):
279
+ chinese_check = gr.Checkbox(label="Chinese Prompt Mode(中文提示词模式)", info="Click here to enable Chinese Prompting(点此触发中文提示词输入)")
280
+ image_box = gr.ImageEditor(sources=(), brush=gr.Brush(default_size="5", color_mode="fixed", colors=["#000000"]), height=400)
281
+
282
+ gen_btn = gr.Button(value="Generate(生成)")
283
+ with gr.Row(equal_height=True):
284
+ image1 = gr.Image(label="Result 1(结果图 1)")
285
+ image2 = gr.Image(label="Result 2(结果图 2)")
286
+ image3 = gr.Image(label="Result 3(结果图 3)")
287
+ image4 = gr.Image(label="Result 4(结果图 4)")
288
+ # sketch_image_box.change(fn=mult_thread_scribble, inputs=[prompt_box, neg_prompt_box, sketch_image_box], outputs=[image1, image2, image3, image4])
289
+ example_scribble_live2img = [
290
+ ["帅气的男孩,橙色头发++,皱眉,闭眼,深蓝色开襟毛衣,白色内衬,酷,冷漠,帅气,硝烟背景", "劣质", "sketch_boy.png"],
291
+ ["a beautiful girl spreading her arms, blue hair, long hair, hat with flowers on its edge, smiling++, dynamic, black dress, park background, birds, trees, flowers, grass","ugly, worst quality", "girl_spread.jpg"]
292
+ ]
293
+
294
+ gr.Examples(examples=example_scribble_live2img, inputs=[prompt_box, neg_prompt_box, image_box], outputs=[image1, image2, image3, image4], fn=mult_thread_live_scribble, cache_examples=True)
295
+
296
+ gr.on(triggers=[prompt_box.submit, gen_btn.click],fn=mult_thread_lang_class, inputs=[prompt_box, neg_prompt_box, chinese_check], outputs=[chinese_check], show_progress=False)
297
+ gr.on(triggers=[prompt_box.submit, gen_btn.click],fn=mult_thread_live_scribble, inputs=[prompt_box, neg_prompt_box, image_box], outputs=[image1, image2, image3, image4])
298
+
299
+ with gr.Tab("AniSketch(安妮涂鸦)"):
300
+ gr.Markdown(
301
+ """
302
+ # AniSketch(安妮涂鸦)
303
+ Turns sketches/scribbles into one in the anime style.
304
+ 将草图、粗线条涂鸦转为动漫风图片。
305
+ """
306
+ )
307
+ with gr.Row(equal_height=True):
308
+ with gr.Column():
309
+ with gr.Row(equal_height=True):
310
+ with gr.Column(scale=4):
311
+ prompt_box = gr.Textbox(label="Prompt(提示词)", placeholder="Enter a prompt\n输入提示词", lines=3)
312
+ neg_prompt_box = gr.Textbox(label="Negative Prompt(负面提示词)", placeholder="Enter a negative prompt(things you don't want to include in the generated image)\n输入负面提示词:输入您不想生成的部分", lines=3)
313
+ with gr.Row(equal_height=True):
314
+ chinese_check = gr.Checkbox(label="Chinese Prompt Mode(中文提示词模式)", info="Click here to enable Chinese Prompting(点此触发中文提示词输入)")
315
+ image_box = gr.Image(label="Input Image(上传图片)", height=400)
316
+
317
+ gen_btn = gr.Button(value="Generate(生成)")
318
+ with gr.Row(equal_height=True):
319
+ image1 = gr.Image(label="Result 1(结果图 1)")
320
+ image2 = gr.Image(label="Result 2(结果图 2)")
321
+ image3 = gr.Image(label="Result 3(结果图 3)")
322
+ image4 = gr.Image(label="Result 4(结果图 4)")
323
+ example_scribble2img = [
324
+ ["漂亮的女人,散开的长发,巫师,巫师袍,微笑,拍手,优雅,成熟,月夜背景", "水印", "final_witch.jpg"],
325
+ ["a man wearing a chinese clothes, closed eyes, handsome face, dragon on the clothes, expressionless face, indifferent, chinese building background","poor quality", "chinese_man.jpg"]
326
+ ]
327
+
328
+ gr.Examples(examples=example_scribble2img, inputs=[prompt_box, neg_prompt_box, image_box], outputs=[image1, image2, image3, image4], fn=mult_thread_scribble, cache_examples=True)
329
+
330
+ gr.on(triggers=[prompt_box.submit, gen_btn.click],fn=mult_thread_lang_class, inputs=[prompt_box, neg_prompt_box, chinese_check], outputs=[chinese_check], show_progress=False)
331
+ gr.on(triggers=[prompt_box.submit, gen_btn.click],fn=mult_thread_scribble, inputs=[prompt_box, neg_prompt_box, image_box], outputs=[image1, image2, image3, image4])
332
+
333
+
334
+ def run():
335
+ iface.queue(default_concurrency_limit=20).launch(debug=True, share=True)
336
+
337
+ run()
338
+
339
+ """# Separator
340
+
341
+ """
342
+
343
+