KeyError whilst using streamlit drawable canvas

So I have just started using streamlit drawable canvas by @andfanilo and I just ran into a KeyError even though I basically copy and pasted his code as it was. Could someone help me understand why this is happened and what I should do to rectify it.

Error:
KeyError: ‘fill’

Traceback:

File "~/script_runner.py", line 552, in _run_script
    exec(code, module.__dict__)File "~/app.py", line 107, in <module>
    df["label"] = df["fill"].map(st.session_state["color_to_label"])
File "~/frame.py", line 3761, in __getitem__
    indexer = self.columns.get_loc(key)
File "~range.py", line 349, in get_loc
    raise KeyError(key)

This was the code I used

import streamlit as st
from PIL import Image
import pandas as pd
from streamlit_drawable_canvas import st_canvas

if __name__ == "__main__":
    if "color_to_label" not in st.session_state:
        st.session_state["color_to_label"] = {}

bg_image = Image.open("img/annotation.jpeg")
label_color = (
	st.sidebar.color_picker("Annotation color: ", "#EA1010") + "77"
)  # for alpha from 00 to FF
label = st.sidebar.text_input("Label", "Default")
mode = "transform" if st.sidebar.checkbox("Move ROIs", False) else "rect"

canvas_result = st_canvas(
	fill_color=label_color,
	stroke_width=3,
	background_image=bg_image,
	height=320,
	width=512,
	drawing_mode=mode,
	key="color_annotation_app",
)
if canvas_result.json_data is not None:
	df = pd.json_normalize(canvas_result.json_data["objects"])
	if len(df) == 0:
		return
	st.session_state["color_to_label"][label_color] = label
	df["label"] = df["fill"].map(st.session_state["color_to_label"])
	st.dataframe(df[["top", "left", "width", "height", "fill", "label"]])

with st.expander("Color to label mapping"):
	st.json(st.session_state["color_to_label"])

Hi @streamlit_beginner!

From the error message, it seems that the df DataFrame does not contain the column “fill”. To resolve the issue, I believe you would need to add a condition to check whether the column “fill” exists in the DataFrame df.

Can you please confirm that it is indeed what was missing?

Thanks! :slight_smile:

Charly

Hi Charly, thanks so much for helping, that did help. However, my question is why is it in my code I needed this condition however the original (which I have pasted below) code which was from the author it worked perfectly fine.

import numpy as np
import pandas as pd
import streamlit as st
from PIL import Image
from streamlit_drawable_canvas import st_canvas
from svgpathtools import parse_path


def main():
    if "color_to_label" not in st.session_state:
        st.session_state["color_to_label"] = {}
        



def color_annotation_app():
    bg_image = Image.open("img/annotation.jpeg")
    label_color = (
        st.sidebar.color_picker("Annotation color: ", "#EA1010") + "77"
    )  # for alpha from 00 to FF
    label = st.sidebar.text_input("Label", "Default")
    mode = "transform" if st.sidebar.checkbox("Move ROIs", False) else "rect"

    canvas_result = st_canvas(
        fill_color=label_color,
        stroke_width=3,
        background_image=bg_image,
        height=320,
        width=512,
        drawing_mode=mode,
        key="color_annotation_app",
    )
    if canvas_result.json_data is not None:
        df = pd.json_normalize(canvas_result.json_data["objects"])
        if len(df) == 0:
            return
        st.session_state["color_to_label"][label_color] = label
        df["label"] = df["fill"].map(st.session_state["color_to_label"])
        st.dataframe(df[["top", "left", "width", "height", "fill", "label"]])

    with st.expander("Color to label mapping"):
        st.json(st.session_state["color_to_label"])




if __name__ == "__main__":
    main()
    color_annotation_app()

I think you can check if ‘fill’ exists in your DataFrame columns before trying to access it, e.g. like this:

if canvas_result.json_data is not None:
    df = pd.json_normalize(canvas_result.json_data["objects"])
    if len(df) == 0 or 'fill' not in df.columns:
        return
    st.session_state["color_to_label"][label_color] = label
    df["label"] = df["fill"].map(st.session_state["color_to_label"])
    st.dataframe(df[["top", "left", "width", "height", "fill", "label"]])

Thanks,
Charly

Thank you so much for you help! I appreciate you.

1 Like

You’re welcome!

Happy Streamlit’in’! :balloon:

Charly

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.