Skip to content

Commit

Permalink
Add background color demo
Browse files Browse the repository at this point in the history
  • Loading branch information
snehankekre committed May 2, 2024
1 parent 4583be1 commit 22d5a57
Show file tree
Hide file tree
Showing 5 changed files with 301 additions and 0 deletions.
124 changes: 124 additions & 0 deletions 1.34/background-colors/0_🎨_About.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import streamlit as st

st.set_page_config(
page_title="About background colors",
page_icon="🎨",
)

st.title("🎨 Background colors for text")

st.markdown(
"""This feature adds support for background colors for text in markdown commands. It supports the following colors:"""
)
st.markdown(
"""
- :blue-background[blue]
- :green-background[green]
- :red-background[red]
- :violet-background[violet]
- :orange-background[orange]
- :gray-background[gray], :grey-background[or grey]
- :rainbow-background[rainbow]
"""
)
st.markdown(
"""To add a background color to some text, type `:color-background[text to be colored]`, where `color` needs to be replaced with the name of one of the supported background colors above."""
)

with st.expander("How to use this app"):
st.markdown(
"""
If you're in a hurry, you can jump straight into the [examples](#examples-with-st-markdown) below to see how background colors work across different Streamlit commands.
In case you want to play around with the background colors yourself, check out:
"""
)

st.page_link(
"pages/1_🛝_Playground.py",
label="**Playground** to experiment with different background colors and text.",
icon="🛝",
)
st.page_link(
"pages/2_🏷️_Named_Entity_Recognition.py",
label="**Named Entity Recognition** to see named entities highlighted with different colors.",
icon="🏷️",
)
st.page_link(
"pages/3_😊_Sentiment_Analysis.py",
label="**Sentiment Analysis** to see text highlighted based on sentiment polarity.",
icon="😊",
)

"## Examples with `st.markdown`"
st.markdown(
"""This is :green-background[important].
This is :green-background[important]. :blue-background[This is blue]
:blue-background[This is blue]. This is :red-background[important]
This is :red-background[important]. This is :violet-background[important].
This is :rainbow-background[important many many words].
This is :red-background[important]. :blue-background[This is blue] We should not have match here which is great! This is :red-background[important]. :blue-background[This is blue]
"""
)

"## Other commands"
with st.echo():
st.title("This is :red-background[red].")
st.header("This is :red-background[red].")
st.subheader("This is :red-background[red].")
with st.echo():
st.write("## This is :red-background[red].")
st.write("#### This is :red-background[red].")
with st.echo():
st.slider("This is :red-background[red].")
st.expander("This is :red-background[red].").write("Hello")
st.button("This is :red-background[red].")

"## Edge cases"
with st.echo():
st.markdown(
"This opens a background color tag :red-background[but doesn't close it."
)
with st.echo():
st.markdown(
"This opens a background color tag :red-background[and then opens a different :blue-background[one."
)
with st.echo():
st.markdown("This is **:blue-background[colored] inside bold**.")
with st.echo():
st.markdown(":blue-background[This is **bold**].")

"## Background color is also supported on labels"
with st.echo():
st.button("Background color is :red-background[supported on buttons]!")
with st.echo():
st.download_button(
"Background color is :rainbow-background[supported on download buttons]!",
data=bytes(1234),
)
with st.form("Background color form"):
st.text_input(":blue-background[Background color is supported on labels]")
submitted = st.form_submit_button(
"Background color is :blue-background[supported on form submit buttons]!"
)
with st.echo():
st.checkbox(":violet-background[Also supported on checkboxes!]")
with st.expander(":orange-background[Background color is supported on expanders]"):
st.write(""":blue-background[It is supported on write!]""")
with st.echo():
tabA, tabB = st.tabs(
[
"Background color is :orange-background[supported on tab A]",
":red-background[And is supported on tab B]",
]
)
with tabA:
st.markdown("""It also :blue-background[works perfectly inside of them!]""")

with tabB:
st.write("""It also :blue-background[works perfectly inside of them!]""")
50 changes: 50 additions & 0 deletions 1.34/background-colors/pages/1_🛝_Playground.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import streamlit as st

st.set_page_config(
page_title="Playground",
page_icon="🛝",
)

st.title("🛝 Playground")

st.markdown(
"Select a color and type some text to see it rendered with the selected background color."
)

col1, col2 = st.columns(2)

with col1:
# Color options
color_options = {
"Rainbow": "rainbow-background",
"Red": "red-background",
"Blue": "blue-background",
"Green": "green-background",
"Orange": "orange-background",
"Gray": "gray-background",
"Violet": "violet-background",
}

# User input for color selection
selected_color = st.radio(
"Choose a background color",
list(color_options.values()),
format_func=lambda x: list(color_options.keys())[
list(color_options.values()).index(x)
].capitalize(),
horizontal=True,
)

# User input for text
user_input = st.text_input("Enter your text here:", value="This is some text")

# Display the colored text
st.markdown(f":{selected_color}[{user_input}]")


with col2:
user_input = st.text_input(
"Type in your text and add one or more background colors",
value=":red-background[This is some text] that has :violet-background[multiple background colors].",
)
st.markdown(user_input)
71 changes: 71 additions & 0 deletions 1.34/background-colors/pages/2_🏷️_Named_Entity_Recognition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import spacy
import streamlit as st

# Load the small English model from spaCy
nlp = spacy.load("en_core_web_sm")

st.set_page_config(
page_title="NER with spaCy",
page_icon="🏷️",
)


def annotate_text(text):
"""Generate annotations for given text."""
doc = nlp(text)
annotated_text = ""
last_idx = 0
for ent in doc.ents:
annotated_text += text[last_idx : ent.start_char]
color = "gray" # Default color if not matched below
if ent.label_ in ["PERSON", "NORP", "GPE"]:
color = "blue"
elif ent.label_ in ["ORG", "EVENT"]:
color = "green"
elif ent.label_ in ["DATE", "TIME"]:
color = "orange"
elif ent.label_ in ["MONEY", "QUANTITY", "ORDINAL", "CARDINAL"]:
color = "red"

# Use Streamlit's markdown with custom background color
annotated_text += f":{color}-background[{text[ent.start_char:ent.end_char]}]"
last_idx = ent.end_char
annotated_text += text[last_idx:] # Append any remaining text
return annotated_text


st.header("NER with spaCy and Streamlit", divider=True)
st.caption(
"""
This demo showcases [Named Entity Recognition (NER)](https://spacy.io/usage/linguistic-features#named-entities) using spaCy and Streamlit.
The text you enter will be analyzed, and named entities will be highlighted with different background colors based on their entity type."""
)

user_input = st.text_area(
"Enter text",
"""Elon Musk, the CEO of Tesla, Inc., announced that the company had chosen Berlin as the site for its European Gigafactory.
The announcement was made on November 12, 2019, during an awards ceremony.
Tesla plans to invest around $4 billion in this new facility, aiming to start production by 2021.
This strategic move is expected to boost the economy of Germany and provide thousands of jobs in the region.""",
height=150,
)

with st.sidebar.expander("Annotation legend", expanded=True):
st.markdown(
"""
The text you enter will be analyzed, and named entities will be highlighted with different background colors based on their entity type.
The colors used are as follows:
- :blue-background[Blue]: PERSON, NORP, GPE
- :green-background[Green]: ORG, EVENT
- :orange-background[Orange]: DATE, TIME
- :red-background[Red]: MONEY, QUANTITY, ORDINAL, CARDINAL
Note: The colors are based on the spaCy entity types, and the color choices are arbitrary.
"""
)

annotated_text = annotate_text(user_input)
# Display the annotated text as markdown in Streamlit
st.markdown(annotated_text)
52 changes: 52 additions & 0 deletions 1.34/background-colors/pages/3_😊_Sentiment_Analysis.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import spacy
import streamlit as st
from spacytextblob.spacytextblob import SpacyTextBlob

st.set_page_config(page_title="Sentiment Analysis", page_icon="😊")

# Load the small English model from spaCy
nlp = spacy.load("en_core_web_sm")
# Add the SpacyTextBlob to the pipeline
nlp.add_pipe("spacytextblob")


def analyze_sentiment(text):
"""Analyze sentiment and return text colored based on polarity at the phrase level."""
doc = nlp(text)
output_text = text # Start with the original text
assessments = doc._.blob.sentiment_assessments.assessments

# Process each assessment and apply colors
for assessment in reversed(assessments):
phrase_list, polarity, _, _ = assessment
phrase = " ".join(phrase_list) # Join the list to form the phrase
start = output_text.rfind(phrase) # Find the last occurrence of the phrase
if start != -1:
end = start + len(phrase)
color = "green" if polarity > 0.1 else "red" if polarity < -0.1 else "gray"
# Slice and insert the color
output_text = (
output_text[:start]
+ f":{color}-background[{phrase}]"
+ output_text[end:]
)

return output_text, assessments


st.header("Sentiment Analysis with Text Highlighting", divider=True)
st.caption(
"This app analyzes the sentiment of the entered text and highlights it based on the [sentiment polarity](https://spacy.io/universe/project/spacy-textblob)."
)

user_input = st.text_area(
"Enter text",
"I love Streamlit! It works great and I use it all the time. Frontend development in HTML and CSS is not fun, so Streamlit is the perfect tool for me to quickly build data web apps.",
)

highlighted_text, assessments = analyze_sentiment(user_input)
st.markdown(highlighted_text)

with st.expander("View sentiment assessments"):
for assessment in assessments:
st.text(assessment)
4 changes: 4 additions & 0 deletions 1.34/background-colors/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
streamlit-nightly==1.33.1.dev20240430
spacy>=3.7.2,<3.8.0
https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.7.1/en_core_web_sm-3.7.1-py3-none-any.whl
spacytextblob

0 comments on commit 22d5a57

Please sign in to comment.