I am facing an issue when rendering colored texts inside a chat message. The color of the text is generated as per the sentiment [I am doing sentiment analysis in chatbot]
The problem is when the page sits there for some time and it’s static and I rerun the script sometimes the color is shown. BUT as soon as I send a new prompt all the colors return to default(while).
This code works perfectly when it’s not rendered as a chat message ie. a normal markdown container.
I did try to add an explicit rerun() but it did not work.
def sentiment_color(sentiment: str) -> str:
# Define a dictionary mapping sentiments to colors
sentiment_colors = {"positive": "green", "negative": "red", "neutral": "blue"}
return sentiment_colors.get(sentiment.lower())
# Display previous messages
for message in st.session_state.messages:
# Displays a chat messages based on its roles stored in streamlit session state.
with st.chat_message(message["role"]):
if message["parts"]:
if message["role"] == "user":
st.markdown(
f"""
{message["parts"]}
:{sentiment_color(str(message["sentiment"]))}[{str(message["sentiment"]).upper()}]
"""
)
else:
st.markdown(message["parts"])
if message["image"]:
image_source = (
"Uploaded Image" if message["role"] == "user" else "Generated Image"
)
st.image(message["image"], caption=image_source, use_container_width=True)
I also tried using CSS styling, but the results were same.
sentiment_color_code = sentiment_color(str(message["sentiment"]))
st.markdown(
f"""
{message["parts"]}
<span style="color: {sentiment_color_code}; font-weight: bold;">
[{str(message["sentiment"]).upper()}]
</span>
""",
unsafe_allow_html=True,
)
Expected Solution:
The sentiments are colored as per their properties and properly rendered in the chat.
Static Page when rerun:
(ignore the random text)
When I send a new message:
(it goes back to default)
Python 3.12.4
Streamlit 1.41.1
The app is locally deployed.
Solution:
Check any overriding CSS in your browser due to extensions or customizations.
Thanks, @edsaac for pointing it out.