Created
July 17, 2023 17:59
-
-
Save esnya/9276c87a37e72fc013385693b5e42d19 to your computer and use it in GitHub Desktop.
Custom script for AUTOMATIC1111/stable-diffusion-webui to generate face expressions of anime characters. Powered by cascade classifier from nagadomi/lbpcascade_animeface.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Easy Anime Face Expressions | |
Custom script for AUTOMATIC1111/stable-diffusion-webui to generate face expressions of anime characters. | |
Powered by cascade classifier from nagadomi/lbpcascade_animeface. | |
Usage: | |
1. Download this file to `scripts/easy_anime_face_expressions.py`. | |
2. Start the webui. | |
3. Generate base image with "closed mouth" in prompt. (or first expression tag you will put into the textbox.) | |
4. Press to "Send to img2img" to send the image and the prompt to img2img. | |
5. Select "img2img" tab. | |
6. Select "Easy Face Expressions" script from the dropdown menu "Script". | |
7. Press "Load defaults" button to load default values. (or fill the values manually.) | |
9. Press "Generate" button. And wait for the result. | |
License: | |
MIT License | |
Copyright (c) 2023 esnya | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in | |
all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
THE SOFTWARE. | |
""" | |
from pathlib import Path | |
from typing import Any, Callable, cast | |
from httpx import request | |
import modules.scripts as scripts | |
from modules.processing import ( | |
fix_seed, | |
process_images, | |
StableDiffusionProcessingImg2Img, | |
) | |
from modules.images import ( | |
save_image, | |
draw_grid_annotations, | |
image_grid, | |
GridAnnotation, | |
) | |
import gradio as gr | |
import cv2 | |
from PIL import Image | |
import numpy as np | |
from modules.shared import opts | |
default_expressions = ", ".join( | |
{ | |
tag: tag | |
for tag in [ | |
"closed mouth", | |
# tag group:face tags | |
"angry", | |
"anger vein", | |
"annoyed", | |
"clenched teeth", | |
"scowl", | |
"annoyed", | |
"blush", | |
"blush stickers", | |
"embarrassed", | |
"full-face blush", | |
"nose blush", | |
"bored", | |
"closed eyes", | |
"confused", | |
"crazy", | |
"desperation", | |
"determined", | |
"disappointed", | |
"disdain", | |
"disgust", | |
"despair", | |
"drunk", | |
"envy", | |
"evil", | |
"excited", | |
"exhausted", | |
"expressionless", | |
# "facepalm", | |
"flustered", | |
"frustrated", | |
"furrowed brow", | |
"grimace", | |
"guilt", | |
"happy", | |
"kubrick stare", | |
"lonely", | |
"nervous", | |
"nosebleed", | |
"one eye closed", | |
"open mouth", | |
"parted lips", | |
"pain", | |
"pout", | |
"raised eyebrow", | |
"rolling eyes", | |
"sad", | |
"depressed", | |
"frown", | |
"gloom", | |
"tears", | |
"scared", | |
"panicking", | |
"worried", | |
"serious", | |
"sigh", | |
"sleepy", | |
"sulking", | |
"surprised", | |
"thinking", | |
"pensive", | |
"v-shaped eyebrows", | |
"wince", | |
"upset", | |
"crazy smile", | |
"evil smile", | |
# "fingersmile", | |
"forced smile", | |
"glasgow smile", | |
"grin", | |
"evil grin", | |
"light smile", | |
"sad smile", | |
"seductive smile", | |
"stifled laugh", | |
"doyagao", | |
"smirk", | |
"smug", | |
"troll face", | |
"^^^", | |
"color drain", | |
"depressed", | |
"despair", | |
"gloom", | |
"horrified", | |
"screaming", | |
"sobbing", | |
"traumatized", | |
"turn pale", | |
"wavy mouth", | |
"upset", | |
# ";)", | |
# ":d", | |
# ";d", | |
# "xd", | |
# "d:", | |
# ":3", | |
# ";3", | |
# "x3", | |
# "3:", | |
# "uwu", | |
# ":p", | |
# ";p", | |
# ":q", | |
# ";q", | |
# ">:)", | |
# ">:(", | |
# ":t", | |
# ":i", | |
# ":/", | |
# ":|", | |
# ":x", | |
# ":c", | |
# "c:", | |
# ":<", | |
# ";<", | |
"diamond mouth", | |
# ":>", | |
# ":>=", | |
# ":o", | |
# ";o", | |
# "o3o", | |
# ">3<", | |
# "o_o", | |
# "0_0", | |
# "|_|", | |
# "._.", | |
"solid circle eyes", | |
"heart-shaped eyes", | |
# "^_^", | |
# "^o^", | |
# "\\(^o^)/", | |
# "^q^", | |
# ">_<", | |
# "xd", | |
# "x3", | |
# ">o<", | |
# "@_@", | |
# ">_@", | |
# "+_+", | |
# "+_-", | |
# "=_=", | |
# "=^=", | |
# "=v=", | |
# "<o>_<o>", | |
# "<|>_<|>", | |
"chestnut mouth", | |
"constricted pupils", | |
"cross-eyed", | |
"dot mouth", | |
"dot nose", | |
"mouth drool", | |
"no nose", | |
"no mouth", | |
"rectangular mouth", | |
"sideways mouth", | |
"split mouth", | |
"wavy mouth", | |
"wide-eyed", | |
"awesome face", | |
# "face of the people who sank all their money into the fx", | |
"foodgasm", | |
"henohenomoheji", | |
"nonowa", | |
"portrait", | |
"profile", | |
"smiley face", | |
"troll face", | |
"uso da", | |
"breast awe", | |
"food awe", | |
"muscle awe", | |
"staring", | |
] | |
}.values() | |
) | |
default_face_classifier = "lbpcascade_animeface" | |
default_min_neighbors = 9 | |
default_scale_factor = 1.01 | |
default_min_size = 128 | |
default_mask_scaling = 0.9 | |
default_mask_blur_size = 255 | |
def load_defaults_fn(): | |
return [ | |
default_expressions, | |
default_face_classifier, | |
default_min_neighbors, | |
default_scale_factor, | |
default_min_size, | |
default_mask_scaling, | |
default_mask_blur_size, | |
] | |
def opts_setter(key: str) -> Callable[[Any], None]: | |
def setter(value): | |
opts.set(key, value) | |
return setter | |
def generate_face_mask( | |
image: Image.Image, | |
classifier: str, | |
min_neighbors: int, | |
scale_factor: float, | |
min_size: int, | |
mask_scaling: float, | |
mask_blur_size: float, | |
): | |
mask = np.zeros_like(image) | |
cascade = cv2.CascadeClassifier(classifier) | |
gray = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY) | |
faces = cascade.detectMultiScale( | |
gray, | |
minNeighbors=min_neighbors, | |
scaleFactor=scale_factor, | |
minSize=(min_size, min_size), | |
) | |
if len(faces) == 0: | |
return None | |
for x, y, w, h in faces: | |
top_left = np.array((x, y)) | |
size = (np.array((w, h)) * mask_scaling).astype(int) | |
center = top_left + size // 2 | |
axes = size // 2 | |
cv2.ellipse(mask, center, axes, 0, 0, 360, (255, 255, 255), -1) | |
if mask_blur_size > 0: | |
if mask_blur_size % 2 == 0: | |
mask_blur_size += 1 | |
cv2.GaussianBlur(mask, (mask_blur_size, mask_blur_size), 0, dst=mask) | |
return Image.fromarray(mask) | |
class Script(scripts.Script): | |
def title(self): | |
return "Easy Anime Face Expressions" | |
def show(self, is_img2img): | |
return is_img2img | |
def ui(self, _): | |
with gr.Row(elem_id=self.elem_id("prompt")): | |
expressions = gr.Textbox( | |
default=default_expressions, | |
lines=1, | |
label="Expression Tags", | |
elem_id=self.elem_id("expressions"), | |
) | |
with gr.Row(elem_id=self.elem_id("classifier")): | |
face_classifier = gr.Textbox( | |
default=default_face_classifier, | |
lines=1, | |
label="Face classifier", | |
elem_id=self.elem_id("face_classifier"), | |
) | |
min_neighbors = gr.Number( | |
default=default_min_neighbors, | |
label="Min neighbors", | |
min_value=0, | |
step=1, | |
elem_id=self.elem_id("min_neighbors"), | |
) | |
scale_factor = gr.Number( | |
default=default_scale_factor, | |
label="Scale factor", | |
min_value=1.0, | |
step=0.01, | |
elem_id=self.elem_id("scale_factor"), | |
) | |
min_size = gr.Number( | |
default=default_min_size, | |
label="Min size", | |
min_value=1, | |
step=1, | |
elem_id=self.elem_id("min_size"), | |
) | |
mask_scaling = gr.Number( | |
default=default_mask_scaling, | |
label="Mask scaling", | |
min_value=0.0, | |
step=0.1, | |
elem_id=self.elem_id("mask_scaling"), | |
) | |
mask_blur_size = gr.Number( | |
default=default_mask_blur_size, | |
label="Mask blur size", | |
min_value=0, | |
max_value=1, | |
step=1, | |
elem_id=self.elem_id("mask_blur_size"), | |
) | |
with gr.Row(): | |
grid_save = gr.Checkbox( | |
default=opts.grid_save, | |
label="Save grid", | |
elem_id=self.elem_id("grid_save"), | |
) | |
grid_save.change(opts_setter("grid_save"), inputs=[grid_save]) | |
save_mask = gr.Checkbox( | |
default=opts.save_mask, | |
label="Save mask", | |
elem_id=self.elem_id("mask_save"), | |
) | |
save_mask.change(opts_setter("save_mask"), inputs=[save_mask]) | |
with gr.Row(): | |
load_defaults = gr.Button( | |
"Load defaults", | |
elem_id=self.elem_id("load_defaults"), | |
) | |
load_defaults.click( | |
load_defaults_fn, | |
outputs=[ | |
expressions, | |
face_classifier, | |
min_neighbors, | |
scale_factor, | |
min_size, | |
mask_scaling, | |
mask_blur_size, | |
], | |
) | |
return [ | |
expressions, | |
face_classifier, | |
min_neighbors, | |
scale_factor, | |
min_size, | |
mask_scaling, | |
mask_blur_size, | |
] | |
def run( | |
self, | |
p: StableDiffusionProcessingImg2Img, | |
expressions: Any, | |
face_classifier: Any, | |
min_neighbors: Any, | |
scale_factor: Any, | |
min_size: Any, | |
mask_scaling: Any, | |
mask_blur_size: Any, | |
): | |
if face_classifier is None: | |
face_classifier = default_face_classifier | |
face_classifier_path = Path("models/face_classifier") / Path(face_classifier) | |
if not face_classifier_path.suffix: | |
face_classifier_path = face_classifier_path.with_suffix(".xml") | |
if not face_classifier_path.is_file(): | |
face_classifier_path.parent.mkdir(parents=True, exist_ok=True) | |
print( | |
"Downloading lbpcascade_animeface.xml from https://github.com/nagadomi/lbpcascade_animeface" | |
) | |
url = "https://raw.githubusercontent.com/nagadomi/lbpcascade_animeface/master/lbpcascade_animeface.xml" | |
with open(face_classifier_path, "wb") as f: | |
f.write(request("GET", url).content) | |
fix_seed(p) | |
expression_list = [expression.strip() for expression in expressions.split(",")] | |
num_expressions = len(expression_list) | |
original_prompt = p.prompt | |
p.prompt = cast( | |
Any, | |
[ | |
original_prompt.replace(expression_list[0], expression) | |
for expression in expression_list | |
], | |
) | |
p.image_mask = generate_face_mask( | |
p.init_images[0], | |
str(face_classifier_path), | |
int(min_neighbors), | |
scale_factor, | |
int(min_size), | |
mask_scaling, | |
int(mask_blur_size), | |
) | |
p.n_iter = num_expressions | |
p.prompt_for_display = original_prompt | |
processed = process_images(p) | |
images = [ | |
image for image in processed.images if image.size == (p.width, p.height) | |
] | |
if len(images) != len(processed.images): | |
grid = image_grid(images, p.batch_size, 1) | |
cols, rows = num_expressions, 1 | |
grid = draw_grid_annotations( | |
grid, | |
p.width, | |
p.height, | |
[ | |
[GridAnnotation(text=expression)] * rows | |
for expression in expression_list | |
], | |
[[GridAnnotation(text="", is_active=False)] * cols], | |
) | |
processed.images = [ | |
grid, | |
*images, | |
] | |
if opts.grid_save: | |
save_image( | |
grid, | |
p.outpath_grids, | |
"grid", | |
cast(list, p.all_seeds)[0], | |
cast(list, p.all_prompts)[0], | |
opts.grid_format, | |
info=processed.info, | |
short_filename=not opts.grid_extended_filename, | |
p=p, | |
grid=True, | |
) | |
return processed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment