kevinqu7's picture
update examples
31dc6ee
Raw History Blame
18.4 kB
# Copyright 2024 Anton Obukhov, ETH Zurich. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# --------------------------------------------------------------------------
# If you find this code useful, we kindly ask you to cite our paper in your work.
# Please find bibtex at: https://github.com/prs-eth/Marigold#-citation
# More information about the method can be found at https://marigoldmonodepth.github.io
# --------------------------------------------------------------------------
from __future__ import annotations
import functools
import os
import tempfile
import warnings
import spaces
import gradio as gr
import numpy as np
import torch as torch
from PIL import Image
from diffusers import UNet2DConditionModel
from gradio_imageslider import ImageSlider
from huggingface_hub import login
from gradio_patches.examples import Examples
from gradio_patches.flagging import HuggingFaceDatasetSaver, FlagMethod
from marigold_normals_estimation import MarigoldNormalsPipeline
warnings.filterwarnings(
"ignore", message=".*LoginButton created outside of a Blocks context.*"
)
default_seed = 2024
default_image_denoise_steps = 4
default_image_ensemble_size = 1
default_image_processing_res = 768
default_image_reproducuble = True
default_share_always_show_hf_logout_btn = True
default_share_always_show_accordion = False
def process_image_check(path_input):
if path_input is None:
raise gr.Error(
"Missing image in the first pane: upload a file or use one from the gallery below."
)
def process_image(
pipe,
path_input,
denoise_steps=default_image_denoise_steps,
ensemble_size=default_image_ensemble_size,
processing_res=default_image_processing_res,
):
name_base, name_ext = os.path.splitext(os.path.basename(path_input))
print(f"Processing image {name_base}{name_ext}")
path_output_dir = tempfile.mkdtemp()
path_out_fp32 = os.path.join(path_output_dir, f"{name_base}_normals_fp32.npy")
path_out_16bit = os.path.join(path_output_dir, f"{name_base}_normals_16bit.png")
path_out_vis = os.path.join(path_output_dir, f"{name_base}_normals.png")
input_image = Image.open(path_input)
pipe_out = pipe(
input_image,
denoising_steps=denoise_steps,
ensemble_size=ensemble_size,
processing_res=processing_res,
batch_size=1 if processing_res == 0 else 0, # TODO: do we abuse "batch size" notation here?
seed=default_seed,
show_progress_bar=True,
)
normals_pred = pipe_out.normals_np
normals_colored = pipe_out.normals_colored
# normals_16bit = ((normals_pred + 1.0) * 32767.5).astype(np.uint16)
path_output_dir = os.path.splitext(path_input)[0] + "_output"
os.makedirs(path_output_dir, exist_ok=True)
np.save(path_out_fp32, normals_pred)
normals_colored.save(path_out_vis)
# Image.fromarray(normals_16bit).save(path_out_16bit, mode="I;16")
return (
[path_input, path_out_vis], # TODO: should we unify and output rgb here in depth too?
[path_out_vis, path_out_fp32], # TODO: reintroduce 16bit pngs if it supports 3 channels
)
def run_demo_server(pipe, hf_writer=None):
process_pipe_image = spaces.GPU(functools.partial(process_image, pipe), duration=120)
gradio_theme = gr.themes.Default()
with gr.Blocks(
theme=gradio_theme,
title="Marigold Normals Estimation",
css="""
#download {
height: 118px;
}
.slider .inner {
width: 5px;
background: #FFF;
}
.viewport {
aspect-ratio: 4/3;
}
.tabs button.selected {
font-size: 20px !important;
color: crimson !important;
}
h1 {
text-align: center;
display: block;
}
h2 {
text-align: center;
display: block;
}
h3 {
text-align: center;
display: block;
}
.md_feedback li {
margin-bottom: 0px !important;
}
""",
head="""
<script async src="https://www.googletagmanager.com/gtag/js?id=G-1FWSVCGZTG"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-1FWSVCGZTG');
</script>
""",
) as demo:
if hf_writer is not None:
print("Creating login button")
share_login_btn = gr.LoginButton(size="sm", scale=1, render=False)
print("Created login button")
share_login_btn.activate()
print("Activated login button")
gr.Markdown(
"""
# Marigold Normals Estimation
<p align="center">
<a title="Website" href="https://marigoldmonodepth.github.io/" target="_blank" rel="noopener noreferrer" style="display: inline-block;">
<img src="https://www.obukhov.ai/img/badges/badge-website.svg">
</a>
<a title="arXiv" href="https://arxiv.org/abs/2312.02145" target="_blank" rel="noopener noreferrer" style="display: inline-block;">
<img src="https://www.obukhov.ai/img/badges/badge-pdf.svg">
</a>
<a title="Github" href="https://github.com/prs-eth/marigold" target="_blank" rel="noopener noreferrer" style="display: inline-block;">
<img src="https://img.shields.io/github/stars/prs-eth/marigold?label=GitHub%20%E2%98%85&logo=github&color=C8C" alt="badge-github-stars">
</a>
<a title="Social" href="https://twitter.com/antonobukhov1" target="_blank" rel="noopener noreferrer" style="display: inline-block;">
<img src="https://www.obukhov.ai/img/badges/badge-social.svg" alt="social">
</a>
</p>
"""
)
def get_share_instructions(is_full):
out = (
"### Help us improve Marigold! If the output is not what you expected, "
"you can help us by sharing it with us privately.\n"
)
if is_full:
out += (
"1. Sign into your Hugging Face account using the button below.\n"
"1. Signing in may reset the demo and results; in that case, process the image again.\n"
)
out += "1. Review and agree to the terms of usage and enter an optional message to us.\n"
out += "1. Click the 'Share' button to submit the image to us privately.\n"
return out
def get_share_conditioned_on_login(profile: gr.OAuthProfile | None):
state_logged_out = profile is None
return get_share_instructions(is_full=state_logged_out), gr.Button(
visible=(state_logged_out or default_share_always_show_hf_logout_btn)
)
with gr.Row():
with gr.Column():
image_input = gr.Image(
label="Input Image",
type="filepath",
)
with gr.Accordion("Advanced options", open=True):
image_ensemble_size = gr.Slider(
label="Ensemble size",
minimum=1,
maximum=10,
step=1,
value=default_image_ensemble_size,
)
image_denoise_steps = gr.Slider(
label="Number of denoising steps",
minimum=1,
maximum=20,
step=1,
value=default_image_denoise_steps,
)
image_processing_res = gr.Radio(
[
("Native", 0),
("Recommended", 768),
],
label="Processing resolution",
value=default_image_processing_res,
)
with gr.Row():
image_submit_btn = gr.Button(value="Compute Normals", variant="primary")
image_reset_btn = gr.Button(value="Reset")
with gr.Column():
image_output_slider = ImageSlider(
label="Predicted normals",
type="filepath",
show_download_button=True,
show_share_button=True,
interactive=False,
elem_classes="slider",
position=0.25,
)
image_output_files = gr.Files(
label="Output files",
elem_id="download",
interactive=False,
)
if hf_writer is not None:
with gr.Accordion(
"Feedback",
open=False,
visible=default_share_always_show_accordion,
) as share_box:
share_instructions = gr.Markdown(
get_share_instructions(is_full=True),
elem_classes="md_feedback",
)
share_transfer_of_rights = gr.Checkbox(
label="(Optional) I own or hold necessary rights to the submitted image. By "
"checking this box, I grant an irrevocable, non-exclusive, transferable, "
"royalty-free, worldwide license to use the uploaded image, including for "
"publishing, reproducing, and model training. [transfer_of_rights]",
scale=1,
)
share_content_is_legal = gr.Checkbox(
label="By checking this box, I acknowledge that my uploaded content is legal and "
"safe, and that I am solely responsible for ensuring it complies with all "
"applicable laws and regulations. Additionally, I am aware that my Hugging Face "
"username is collected. [content_is_legal]",
scale=1,
)
share_reason = gr.Textbox(
label="(Optional) Reason for feedback",
max_lines=1,
interactive=True,
)
with gr.Row():
share_login_btn.render()
share_share_btn = gr.Button(
"Share", variant="stop", scale=1
)
Examples(
fn=process_pipe_image,
examples=[
os.path.join("files", "image", name)
for name in [
"berries.jpeg",
"costumes.png",
"puzzle.jpeg",
"einstein.jpg",
"books.jpg",
"juices.jpeg",
"icecream.jpg",
"cat.jpg",
"food_counter.png",
"tent.jpg",
"cat2.png",
"rocket.png",
"food.jpeg",
"screw.png",
]
],
inputs=[image_input],
outputs=[image_output_slider, image_output_files],
cache_examples=True,
directory_name="examples_image",
)
### Image tab
if hf_writer is not None:
image_submit_btn.click(
fn=process_image_check,
inputs=image_input,
outputs=None,
preprocess=False,
queue=False,
).success(
get_share_conditioned_on_login,
None,
[share_instructions, share_login_btn],
queue=False,
).then(
lambda: (
gr.Button(value="Share", interactive=True),
gr.Accordion(visible=True),
False,
False,
"",
),
None,
[
share_share_btn,
share_box,
share_transfer_of_rights,
share_content_is_legal,
share_reason,
],
queue=False,
).then(
fn=process_pipe_image,
inputs=[
image_input,
image_denoise_steps,
image_ensemble_size,
image_processing_res,
],
outputs=[image_output_slider, image_output_files],
concurrency_limit=1,
)
else:
image_submit_btn.click(
fn=process_image_check,
inputs=image_input,
outputs=None,
preprocess=False,
queue=False,
).success(
fn=process_pipe_image,
inputs=[
image_input,
image_denoise_steps,
image_ensemble_size,
image_processing_res,
],
outputs=[image_output_slider, image_output_files],
concurrency_limit=1,
)
image_reset_btn.click(
fn=lambda: (
None,
None,
None,
default_image_ensemble_size,
default_image_denoise_steps,
default_image_processing_res,
),
inputs=[],
outputs=[
image_input,
image_output_slider,
image_output_files,
image_ensemble_size,
image_denoise_steps,
image_processing_res,
],
queue=False,
)
if hf_writer is not None:
image_reset_btn.click(
fn=lambda: (
gr.Button(value="Share", interactive=True),
gr.Accordion(visible=default_share_always_show_accordion),
),
inputs=[],
outputs=[
share_share_btn,
share_box,
],
queue=False,
)
### Share functionality
if hf_writer is not None:
share_components = [
image_input,
image_denoise_steps,
image_ensemble_size,
image_processing_res,
image_output_slider,
share_content_is_legal,
share_transfer_of_rights,
share_reason,
]
hf_writer.setup(share_components, "shared_data")
share_callback = FlagMethod(hf_writer, "Share", "", visual_feedback=True)
def share_precheck(
hf_content_is_legal,
image_output_slider,
profile: gr.OAuthProfile | None,
):
if profile is None:
raise gr.Error(
"Log into the Space with your Hugging Face account first."
)
if image_output_slider is None or image_output_slider[0] is None:
raise gr.Error("No output detected; process the image first.")
if not hf_content_is_legal:
raise gr.Error(
"You must consent that the uploaded content is legal."
)
return gr.Button(value="Sharing in progress", interactive=False)
share_share_btn.click(
share_precheck,
[share_content_is_legal, image_output_slider],
share_share_btn,
preprocess=False,
queue=False,
).success(
share_callback,
inputs=share_components,
outputs=share_share_btn,
preprocess=False,
queue=False,
)
demo.queue(
api_open=False,
).launch(
server_name="0.0.0.0",
server_port=7860,
)
def main():
CHECKPOINT = "prs-eth/marigold-normals-v1-1"
CROWD_DATA = "crowddata-marigold-normals-v1-1-space-v1-1"
os.system("pip freeze")
if "HF_TOKEN_LOGIN" in os.environ:
login(token=os.environ["HF_TOKEN_LOGIN"])
auth_token = os.environ.get("KEV_TOKEN")
pipe = MarigoldNormalsPipeline.from_pretrained(CHECKPOINT,token=auth_token)
try:
import xformers
pipe.enable_xformers_memory_efficient_attention()
except:
pass # run without xformers
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
pipe = pipe.to(device)
hf_writer = None
if "HF_TOKEN_LOGIN_WRITE_CROWD" in os.environ:
hf_writer = HuggingFaceDatasetSaver(
os.getenv("HF_TOKEN_LOGIN_WRITE_CROWD"),
CROWD_DATA,
private=True,
info_filename="dataset_info.json",
separate_dirs=True,
)
run_demo_server(pipe, hf_writer)
if __name__ == "__main__":
main()