Spaces:
Running
Running
from shiny import App, Inputs, Outputs, Session, reactive, render, ui | |
from shiny.types import FileInfo, ImgData | |
import asyncio | |
import concurrent.futures | |
import backend | |
import numpy as np | |
from PIL import Image, ImageDraw | |
from pathlib import Path | |
import tempfile | |
def draw_layer_on_image(im: Image) -> Image: | |
"""Draws something on top of an image.""" | |
# Attempting to use thresholds. | |
threshold: int = 1 | |
output_im = np.array(im) | |
# return Image.fromarray(output_im) | |
# The image drawing code. | |
draw = ImageDraw.Draw(im) | |
draw.line((0, 0) + im.size, fill=128, width=5) | |
draw.line((0, im.size[1], im.size[0], 0), fill=128) | |
return im | |
# UI: | |
# TITLE ELEMENT, centered | |
# input, centered. | |
# table in middle. Upload, displays image on the left. | |
# arrow in the middle, mask on the right. | |
card_height = '700px' | |
app_ui = ui.page_fixed( | |
ui.input_file("file1", "Upload a sidewalk.", accept=[".jpg", ".png", ".jpeg"], multiple=False), | |
ui.layout_columns( | |
ui.card( | |
ui.card_header("Uploaded Image"), | |
ui.output_image("show_image"), | |
height=card_height | |
), | |
ui.card( | |
ui.card_header("Image Mask"), | |
# ui.input_task_button("mask_btn", "Process mask"), | |
ui.output_image("samwalk"), | |
height=card_height | |
), | |
) | |
) | |
def strip_alpha(image: Image) -> Image: | |
# Create a white background | |
background = Image.new('RGBA', image.size, (255, 255, 255, 255)) | |
composite = Image.alpha_composite(background, image) | |
rgb_image = composite.convert('RGB') | |
return rgb_image | |
def server(input: Inputs, output: Outputs, session: Session): | |
uploaded_img = None | |
def parsed_file(): | |
file: list[FileInfo] | None = input.file1() | |
if file is None: | |
return | |
return file[0] | |
def show_image(): | |
uploaded_img = parsed_file() | |
if uploaded_img is None: | |
return | |
uploaded_src = uploaded_img['datapath'] | |
img: ImgData = {"src": str(uploaded_src), "width": "500px"} | |
return img | |
# @reactive.event(input.mask_btn) | |
def samwalk(): | |
uploaded_file = parsed_file() | |
if uploaded_file is None: | |
return | |
uploaded_src = uploaded_file['datapath'] | |
uploaded_img = Image.open(uploaded_src) | |
if uploaded_img.mode == 'RGBA': | |
uploaded_img = strip_alpha(uploaded_img) | |
dirpath = tempfile.mkdtemp() | |
# output_img = async_process_image(uploaded_img) | |
# while output_img is None: | |
# pass | |
# output_img = output_img.result() | |
# # return {"src": str("waiting.gif"), "width": "500px"} | |
output_img = backend.process_image(uploaded_img) | |
output_path = dirpath / Path(uploaded_src) | |
output_img.save(output_path) | |
return {"src": str(output_path), "width": "500px"} | |
app = App(app_ui, server) | |