Streamlit-pills

code

   from streamlit_pills import pills
   if uploaded_file:
        selected = pills("Label", ["summarise", "explain module 2", "what is cash management?"])
        if selected:
             query=selected

here the above code is selecting the pill without user interaction ,default selection is happening ,how to control default selection,only on user click tht should be selected

Hello,
You got the answer in the documentation :smiley:

pills("Label", ["summarise", "explain module 2", "what is cash management?"], index=None)

Thankyou sm It worked , and one more thing how to unselect once that option is clicked and response is generated ,it should be to initial state .

if uploaded_file is not None:
    with st.spinner('Processing file...'):
        result = process_file(uploaded_file)
    st.success('File processed successfully!')
    # Generate default response after file upload
    # default_response = generate_default_response()
    # st.session_state.history.append(("Bot", default_response))
    # st.session_state.messages.append({"role": "Assistant", "content": default_response})

# Main chat interface
from streamlit_pills import pills
if uploaded_file:
    selected = pills("Label", ["summarise", "explain module 2", "what is cash management?"],index=None)
    if selected:
        query = selected
        if query:
            vector_store = pd.read_sql_query("SELECT * FROM pdfdata;", conn)
            context, top_matched_df = get_context_from_question(query, vector_store)
            generated_text = get_completion(context + " " + query, model="gpt-3.5-turbo")

            # Update conversation history
            st.session_state.history.append(("User", query))
            st.session_state.history.append(("Bot", generated_text))
            st.session_state.messages.append({"role": "User", "content": query})
            st.session_state.messages.append({"role": "Assistant", "content": generated_text})
       
query2 = st.chat_input("Enter your question:")
if query2:
            vector_store = pd.read_sql_query("SELECT * FROM pdfdata;", conn)
            context, top_matched_df = get_context_from_question(query2, vector_store)
            generated_text = get_completion(context + " " + query2, model="gpt-3.5-turbo")

            # Update conversation history
            st.session_state.history.append(("User", query2))
            st.session_state.history.append(("Bot", generated_text))
            st.session_state.messages.append({"role": "User", "content": query2})
            st.session_state.messages.append({"role": "Assistant", "content": generated_text})

here the my file reloading again while asking query so that response is generated twice



see in the above image it giving response twice ,1 for pills ,one for the user input.
please kindly help me out to resolve this

I had the same issue with resetting the selected value in Streamlit pills. After some experimentation, I figured out a way to do it and created a function to handle this easily. Here’s how you can achieve it:

from streamlit_pills import pills
import streamlit as st
from typing import Iterable, Union, Callable

def custom_pills(label: str, options: Iterable[str], icons: Iterable[str] = None, index: Union[int, None] = 0,
                 format_func: Callable = None, label_visibility: str = "visible", clearable: bool = None,
                 key: str = None, reset_key: str = None):
    """
    Displays clickable pills with an option to reset the selection.

    Args:
        label (str): The label shown above the pills.
        options (iterable of str): The texts shown inside the pills.
        icons (iterable of str, optional): The emoji icons shown on the left side of the pills. Each item must be a single emoji. Default is None.
        index (int or None, optional): The index of the pill that is selected by default. If None, no pill is selected. Defaults to 0.
        format_func (callable, optional): A function applied to the pill text before rendering. Defaults to None.
        label_visibility ("visible" or "hidden" or "collapsed", optional): The visibility of the label. Use this instead of `label=""` for accessibility. Defaults to "visible".
        clearable (bool, optional): Whether the user can unselect the selected pill by clicking on it. Default is None.
        key (str, optional): The key of the component. Defaults to None.
        reset_key (str, optional): The key used to reset the selection. Defaults to None.

    Returns:
        (any): The text of the pill selected by the user (same value as in `options`).
    """
    
    # Create a unique key for the component to force update when necessary
    unique_key = f"{key}-{reset_key}" if key and reset_key else key
    
    # Pass the arguments to the pills function
    selected = pills(label=label, options=options, icons=icons, index=index, format_func=format_func,
                     label_visibility=label_visibility, clearable=clearable, key=unique_key)
    
    return selected

# Example usage
if 'selected_option' not in st.session_state:
    st.session_state.selected_option = None
if 'reset_key' not in st.session_state:
    st.session_state.reset_key = 0

# Function to reset the selection
def reset_selection():
    st.session_state.selected_option = None
    st.session_state.reset_key += 1  # Increment the key to force update

# Add a button to reset the selection
if st.button('Reset Selection'):
    reset_selection()

# Use the custom_pills function
selected = custom_pills("Label", ["Option 1", "Option 2", "Option 3"], ["🍀", "🎈", "🌈"], index=None, clearable=True, key="pill", reset_key=str(st.session_state.reset_key))

# Update the selected option in session state
if selected is not None:
    st.session_state.selected_option = selected

st.write("Selected option:", st.session_state.selected_option)

Explanation:

  1. custom_pills Function:
  • Encapsulates the logic for the pills and accepts the same arguments as the original pills function.
  • Adds a reset_key argument to allow forced updates of the component.
  1. Example Usage:
  • Uses st.session_state to store the selected option and a reset key.
  • The reset_selection function resets the selection and increments the reset key.
  • The “Reset Selection” button calls reset_selection to force an update.
  • Calls custom_pills with the appropriate arguments and reset key.
  • Updates the selected option in the session state.

This approach ensures the reset works correctly, forcing the pills component to refresh and clear the selection.

1 Like

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