Spaces:
Runtime error
Runtime error
import gradio as gr | |
from gradio_imageslider import ImageSlider | |
import spaces | |
from transformers import AutoModelForImageSegmentation | |
import torch | |
from torchvision import transforms | |
from PIL import Image | |
torch.set_float32_matmul_precision(["high", "highest"][0]) | |
birefnet = AutoModelForImageSegmentation.from_pretrained( | |
"ZhengPeng7/BiRefNet", trust_remote_code=True | |
) | |
birefnet.to("cuda") | |
transform_image = transforms.Compose( | |
[ | |
transforms.Resize((1024, 1024)), | |
transforms.ToTensor(), | |
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), | |
] | |
) | |
def fn(image): | |
if image is None or len(image) == 0: | |
return image, None # μλ³Έ μ΄λ―Έμ§λ λ°ν | |
im = Image.open(image).convert("RGB") | |
image_size = im.size | |
origin = im.copy() | |
input_images = transform_image(im).unsqueeze(0).to("cuda") | |
# Prediction | |
with torch.no_grad(): | |
preds = birefnet(input_images)[-1].sigmoid().cpu() | |
pred = preds[0].squeeze() | |
pred_pil = transforms.ToPILImage()(pred) | |
mask = pred_pil.resize(image_size) | |
im.putalpha(mask) | |
return im, origin # λ³νλ μ΄λ―Έμ§μ μλ³Έ μ΄λ―Έμ§ λ°ν | |
def save_image(image): | |
if image is not None: | |
image.save("output.png") | |
return "output.png" | |
return None | |
with gr.Blocks() as demo: | |
image = gr.Image(label="Upload an image") | |
text = gr.Textbox(label="Paste an image URL") | |
download_button = gr.Button("Download Image") | |
output_file = gr.File() | |
slider1 = ImageSlider(label="birefnet", type="pil") | |
slider2 = ImageSlider(label="birefnet", type="pil") | |
# μ€νμ΄μ€μ μλ μμ μ΄λ―Έμ§ νμΌ κ²½λ‘ | |
example_image1 = "example_images/example1.jpg" | |
example_image2 = "example_images/example2.jpg" | |
example_image3 = "example_images/example3.jpg" | |
with gr.Tab("Image Upload"): | |
tab1 = gr.Interface( | |
fn, inputs=image, outputs=[slider1, output_file], | |
examples=[example_image1, example_image2, example_image3], api_name="image" | |
) | |
with gr.Tab("Image URL"): | |
tab2 = gr.Interface( | |
fn, inputs=text, outputs=[slider2, output_file], | |
examples=[example_image1, example_image2, example_image3], api_name="text" | |
) | |
def process_download(image): | |
return save_image(image[0]) | |
download_button.click(process_download, inputs=slider1, outputs=output_file) | |
if __name__ == "__main__": | |
demo.launch() | |