Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151from pathlib import Pathfrom typing import List, Dict, Tupleimport matplotlib.colors as mpl_colorsimport pandas as pdimport seaborn as snsimport shinyswatchfrom shiny import App, Inputs, Outputs, Session, reactive, render, req, uisns.set_theme()www_dir = Path(__file__).parent.resolve() / "www"df = pd.read_csv(Path(__file__).parent / "penguins.csv", na_values="NA")numeric_cols: List[str] = df.select_dtypes(include=["float64"]).columns.tolist()species: List[str] = df["Species"].unique().tolist()species.sort()app_ui = ui.page_fillable(shinyswatch.theme.minty(),ui.layout_sidebar(ui.sidebar(# Artwork by @allison_horstui.input_selectize("xvar","X variable",numeric_cols,selected="Bill Length (mm)",),ui.input_selectize("yvar","Y variable",numeric_cols,selected="Bill Depth (mm)",),ui.input_checkbox_group("species", "Filter by species", species, selected=species),ui.hr(),ui.input_switch("by_species", "Show species", value=True),ui.input_switch("show_margins", "Show marginal plots", value=True),),ui.output_ui("value_boxes"),ui.output_plot("scatter", fill=True),ui.help_text("Artwork by ",ui.a("@allison_horst", href="https://twitter.com/allison_horst"),class_="text-end",),),)def server(input: Inputs, output: Outputs, session: Session):@reactive.Calcdef filtered_df() -> pd.DataFrame:"""Returns a Pandas data frame that includes only the desired rows"""# This calculation "req"uires that at least one species is selectedreq(len(input.species()) > 0)# Filter the rows so we only include the desired speciesreturn df[df["Species"].isin(input.species())]@output@render.plotdef scatter():"""Generates a plot for Shiny to display to the user"""# The plotting function to use depends on whether margins are desiredplotfunc = sns.jointplot if input.show_margins() else sns.scatterplotplotfunc(data=filtered_df(),x=input.xvar(),y=input.yvar(),palette=palette,hue="Species" if input.by_species() else None,hue_order=species,legend=False,)@output@render.uidef value_boxes():df = filtered_df()def penguin_value_box(title: str, count: int, bgcol: str, showcase_img: str):return ui.value_box(title,count,{"class_": "pt-1 pb-0"},showcase=ui.fill.as_fill_item(ui.tags.img({"style": "object-fit:contain;"},src=showcase_img,)),theme_color=None,style=f"background-color: {bgcol};",)if not input.by_species():return penguin_value_box("Penguins",len(df.index),bg_palette["default"],# Artwork by @allison_horstshowcase_img="penguins.png",)value_boxes = [penguin_value_box(name,len(df[df["Species"] == name]),bg_palette[name],# Artwork by @allison_horstshowcase_img=f"{name}.png",)for name in species# Only include boxes for _selected_ speciesif name in input.species()]return ui.layout_column_wrap(*value_boxes, width = 1 / len(value_boxes))# "darkorange", "purple", "cyan4"colors = [[255, 140, 0], [160, 32, 240], [0, 139, 139]]colors = [(r / 255.0, g / 255.0, b / 255.0) for r, g, b in colors]palette: Dict[str, Tuple[float, float, float]] = {"Adelie": colors[0],"Chinstrap": colors[1],"Gentoo": colors[2],"default": sns.color_palette()[0], # type: ignore}bg_palette = {}# Use `sns.set_style("whitegrid")` to help find approx alpha valuefor name, col in palette.items():# Adjusted n_colors until `axe` accessibility did not complain about color contrastbg_palette[name] = mpl_colors.to_hex(sns.light_palette(col, n_colors=7)[1]) # type: ignoreapp = App(app_ui,server,static_assets=str(www_dir),)12345678910111213141516171819202122232425262728293031323334from PIL import Imageimport numpy as npimport streamlit as st# Define function to process uploaded imagedef process_image(image):# Convert image to numpy arrayimg_array = np.array(image)# Dummy sidewalk segmentation (replace with your actual segmentation algorithm)segmentation_result = np.zeros_like(img_array)segmentation_result[:, :, 1] = 255 # Set sidewalk area to green (RGB: 0, 255, 0)return segmentation_result# Define Shiny appdef main():st.title("Sidewalk Segmentation App")uploaded_image = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])if uploaded_image is not None:# Display uploaded imageimage = Image.open(uploaded_image)st.image(image, caption="Uploaded Image", use_column_width=True)# Process uploaded imagewith st.spinner("Processing..."):segmentation_result = process_image(image)# Display segmentation resultst.image(segmentation_result, caption="Sidewalk Segmentation Result", use_column_width=True)if __name__ == "__main__":main()
app.py+26-143