Spaces:
Runtime error
Runtime error
File size: 6,665 Bytes
e428a0a ecd427f e428a0a ecd427f e428a0a ecd427f 3806189 e428a0a c49de8e e428a0a 310e819 3806189 ecd427f 3806189 ecd427f 3806189 ecd427f 3806189 c49de8e 3806189 ecd427f e428a0a 1e8371c e428a0a ecd427f e428a0a ecd427f e428a0a ecd427f e428a0a ecd427f 310e819 ecd427f 3806189 ecd427f 3806189 65784d9 310e819 e428a0a bfaad21 e428a0a c49de8e e428a0a ecd427f 3806189 ecd427f 3806189 ecd427f 3806189 ecd427f c49de8e 3806189 be5001e 3806189 0ae8d1b 8a27c03 3806189 ecd427f 3806189 ecd427f c49de8e ecd427f feee856 c49de8e ecd427f c49de8e 3806189 ecd427f 3806189 ecd427f c49de8e ecd427f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel
from diffusers import UniPCMultistepScheduler
import gradio as gr
import numpy as np
import torch
import base64
import cv2
from io import BytesIO
from PIL import Image, ImageFilter
from share_btn import community_icon_html, loading_icon_html, share_js, share_btn_css
# Constants
low_threshold = 100
high_threshold = 200
canvas_html = '<pose-maker/>'
load_js = """
async () => {
const url = "https://huggingface.co/datasets/mishig/gradio-components/raw/main/mannequinAll.js"
fetch(url)
.then(res => res.text())
.then(text => {
const script = document.createElement('script');
script.type = "module"
script.src = URL.createObjectURL(new Blob([text], { type: 'application/javascript' }));
document.head.appendChild(script);
});
}
"""
get_js_image = """
async (canvas, prompt) => {
const poseMakerEl = document.querySelector("pose-maker");
const imgBase64 = poseMakerEl.captureScreenshotDepthMap();
return [imgBase64, prompt]
}
"""
# Models
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/control_v11p_sd15_canny", torch_dtype=torch.float16
)
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=controlnet, safety_checker=None, torch_dtype=torch.float16
)
pipe.scheduler = UniPCMultistepScheduler.from_config(pipe.scheduler.config)
# This command loads the individual model components on GPU on-demand. So, we don't
# need to explicitly call pipe.to("cuda").
pipe.enable_model_cpu_offload()
# xformers
pipe.enable_xformers_memory_efficient_attention()
# Generator seed,
generator = torch.manual_seed(0)
def get_canny_filter(image):
if not isinstance(image, np.ndarray):
image = np.array(image)
image = cv2.Canny(image, low_threshold, high_threshold)
image = image[:, :, None]
image = np.concatenate([image, image, image], axis=2)
canny_image = Image.fromarray(image)
return canny_image
def generate_images(canvas, prompt):
try:
base64_img = canvas
image_data = base64.b64decode(base64_img.split(',')[1])
input_img = Image.open(BytesIO(image_data)).convert(
'RGB').resize((512, 512))
input_img = input_img.filter(ImageFilter.GaussianBlur(radius=2))
input_img = get_canny_filter(input_img)
output = pipe(
f'{prompt}, unreal engine, Flickr, Canon camera, f50, best quality, extremely detailed',
input_img,
generator=generator,
num_images_per_prompt=2,
num_inference_steps=20,
negative_prompt="longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality",
)
all_outputs = []
for image in output.images:
all_outputs.append(image)
return all_outputs
except Exception as e:
raise gr.Error(str(e))
def placeholder_fn(axis):
pass
js_change_rotation_axis = """
async (axis) => {
const poseMakerEl = document.querySelector("pose-maker");
poseMakerEl.changeRotationAxis(axis);
}
"""
js_pose_template = """
async (pose) => {
const poseMakerEl = document.querySelector("pose-maker");
poseMakerEl.setPose(pose);
}
"""
with gr.Blocks(css=share_btn_css) as blocks:
gr.HTML(
"""
<div style="text-align: center; margin: 0 auto;">
<div
style="
display: inline-flex;
align-items: center;
gap: 0.8rem;
font-size: 1.75rem;
"
>
<h1 style="font-weight: 900; margin-bottom: 7px;margin-top:5px">
Pose in 3D & Render with ControlNet (SD-1.5)
</h1>
</div>
<p style="margin-bottom: 10px; font-size: 94%; line-height: 23px;">
Using <a href="https://huggingface.co/blog/controlnet">ControlNet</a> and <a href="https://boytchev.github.io/mannequin.js/">three.js/mannequin.js</a>
</p>
<p style="margin-bottom: 10px; font-size: 94%; line-height: 23px;">
For a comprehensive ControlNet-v1.1 demo, checkout <a href="https://huggingface.co/spaces/hysts/ControlNet-v1-1">hysts/ControlNet-v1-1</a> space
</p>
<p>For faster inference without waiting in queue, you may duplicate the space and upgrade to GPU in settings. <a href="https://huggingface.co/spaces/diffusers/controlnet-3d-pose?duplicate=true"><img style="display: inline; margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space" /></a></p>
</div>
"""
)
with gr.Row():
with gr.Column():
canvas = gr.HTML(canvas_html, elem_id="canvas_html", visible=True)
with gr.Row():
rotation_axis = gr.Radio(["x", "y", "z"], value="x", label="Joint rotation axis")
pose_template = gr.Radio(["regular", "ballet", "handstand", "split", "kick", "chilling"], value="regular", label="Pose template")
prompt = gr.Textbox(
label="Enter your prompt",
max_lines=1,
placeholder="best quality, extremely detailed",
elem_id="prompt",
)
run_button = gr.Button("Generate")
gr.Markdown("### See an example [here](https://huggingface.co/spaces/diffusers/controlnet-3d-pose/discussions/1)")
with gr.Group(elem_id="share-btn-container"):
community_icon = gr.HTML(community_icon_html)
loading_icon = gr.HTML(loading_icon_html)
share_button = gr.Button("Share to community", elem_id="share-btn")
with gr.Column():
gallery = gr.Gallery(elem_id="gallery").style(grid=[2], height="auto")
rotation_axis.change(fn=placeholder_fn,
inputs=[rotation_axis],
outputs=[],
queue=False,
_js=js_change_rotation_axis)
pose_template.change(fn=placeholder_fn,
inputs=[pose_template],
outputs=[],
queue=False,
_js=js_pose_template)
run_button.click(fn=generate_images,
inputs=[canvas, prompt],
outputs=[gallery],
_js=get_js_image)
share_button.click(None, [], [], _js=share_js)
blocks.load(None, None, None, _js=load_js)
blocks.launch(debug=True)
|