I’m trying to create a chatbot using streamlit. I want it to be possible to have a hybrid query of text and a file input. Right now I have created it so that I can click the send button and the input of either the text box, extracted content from the file or both are send to my agent. I want to change it so that I can click the ‘Enter’ button and send it instead of a separate send button.
This is my current code section related to it
if "user_input" not in st.session_state:
st.session_state.user_input = []
if "document_processed" not in st.session_state:
st.session_state.document_processed = False
if "generated_document" not in st.session_state:
st.session_state.generated_document = None
def submit():
if st.session_state.widget.strip():
st.session_state.user_input = st.session_state.widget
st.session_state.widget = ""
st.text_input("Type your message...", key="widget")
document = st.file_uploader("", type=["pdf", "docx"], label_visibility="collapsed", key="file", help="Upload your file.")
if document is not None and "last_uploaded_document" in st.session_state:
if document != st.session_state.last_uploaded_document:
st.session_state.document_processed = False # Reset only for new documents
st.session_state.last_uploaded_document = document # Store the uploaded document in session state
send_b = st.button("Send", on_click=submit)
if send_button:
combined_input = ""
# Extract text from the document if uploaded
if document_file is not None and not st.session_state.document_processed:
if document_file.type == "application/pdf":
document_text = extract_text_from_pdf(document_file)
elif document_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
document_text = extract_text_from_docx(document_file)
else:
st.error("Unsupported file type.")
document_text = ""
combined_input += document_text # Add document text to combined input
st.session_state.document_processed = True # Mark the document as processed
# Add text input to combined input
if user_input:
combined_input += user_input # Add text query to combined input
if combined_input.strip():
st.session_state.user_input = ""
st.session_state.messages.append({"role": "user", "text": combined_input})
log_user_action(f"User sent a message: {combined_input}", username)
Right now once the document is uploaded the extracted content is cleared after being processed once so it isn’t stored and being sent with each new query. The text is also cleared each time send is pressed. I want to maintain all these functionalities just with me being able to press ‘Enter’ instead of send.