Dynamically create selectboxes and save the Selections

Viewed 29

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 AC”
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)

   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
1 Answers

I solved it myself. The idea is to capture the tokens and keys (to uniquely identify selectboxes linked to different tokens) into a dictionary. And then use that dict to get back the state of the current select-box selections. Also passing a custom function to on_change parameter and then send out the key as one of the args can help. Just putting it in there for reference.

 with input_cols:
        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)

save = st.button("Save")

if save:
    #print(changed_tokens)
    for k,v in token_dict.items():
        st.text(v + " --> " + tokenboxes[k])  
Related