Dynamically create selectboxes and save the Selections

Am splitting a text into tokens and for each toke, creating a select box. How would I be able to save the token and the corresponding selected value? Here is my noob attempt.

checkpoint = “bert-base-uncased”

tokenizer = BertTokenizer.from_pretrained(checkpoint)

if “load_state” not in st.session_state:
st.session_state.load_state = False

#txt = “There is a leak on the third floor with the HVAC”
saved = False

txt = st.text_area(“”)
tokenize = st.button(“Tokenize”)
input_cols = st.container()

if tokenize or st.session_state.load_state:
st.session_state.load_state = True
tokens = tokenizer.tokenize(txt)
token_length = len(tokens)
print(token_length)
options = [“L”, “E”]

with input_cols:
    cols = st.columns(token_length)
    for ix, col in enumerate(cols):
        tokenboxes = col.selectbox(tokens[ix], key=ix, options=options)
save = st.button(“Save”)

if save:
st.write(tokenboxes[1]) # the key should exist from above but this index doesnt exist

Hi @Sharat_Sastry,

Thanks for posting! Can you share what’s going wrong with your current attempt?

Caroline

When I posted this @Caroline, I was unable to create multiple select boxes on the fly. This doesnt help:

tokenboxes = col.selectbox(tokens[ix], key=ix, options=options)

I couldn’t reference the boxes back by the key.

One way I tried to solve it was to index each box by ix and then create a dictionary to save the keys and values

        for ix, col in enumerate(cols):
            k = tokens[ix] + "_" +  str(ix)
            token_dict[k] = tokens[ix]
            tokenboxes[k] = col.selectbox(tokens[ix], key=k, options=options, on_change=track_changes, args=(k,), index=0)

But I’m not sure this is the most efficient way to do it. Any suggestions?

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