St.write formatting

Summary

Using line breaks in st.write generates an undesirable look.
I have a string session state variable that I update and render as sort of a ‘story’, thus, there must be paragraphs. However when I add line breaks via \n an undesirable textarea/textbox is created, how can I avoid this from happening?

Steps to reproduce

Code snippet:

import os
import requests
import streamlit as st

def generate_images(prompt, num, output_directory):
    ...

output_directory = "./out/"

st.set_page_config(page_title="Story", page_icon="🧩")

st.title("Interactive Storytelling Experience")

if 'filenames' not in st.session_state:
    st.session_state.filenames = []

if 'captions' not in st.session_state:
    st.session_state.captions = []

if 'story' not in st.session_state:
    st.session_state.story = "Once upon a time...\n"

if 'images' not in st.session_state:
    st.session_state.images = []

if 'last_clicked' not in st.session_state:
    st.session_state.last_clicked = -1

if 'end' not in st.session_state:
    st.session_state.end = False

if 'init' not in st.session_state:
    st.session_state.init = True

prompt_container = st.empty()
prompt = prompt_container.text_area('initprompt', label_visibility="collapsed", key="init_prompt")

text_col, img_col = st.columns(2)

if prompt != "":
    with img_col:
        img_container = st.empty()
    if st.session_state.last_clicked == -1:
        if not st.session_state.end:
            #
            options = [
                "Option 1: Eric decides to intervene directly, using his powers to disarm the robbers and save the hostages.",
                "Option 2: Eric takes a more cautious approach and uses his powers to stealthily gather information about the robbers' plans before alerting the authorities.",
                "Option 3: Eric decides to observe the situation from a safe distance, trying to analyze the criminals' weaknesses and come up with a strategic plan of action.",
                "Option 4: Overwhelmed by the gravity of the situation, Eric hesitates and struggles to decide on the best course of action.",
                "Option 5: Eric realizes that his powers are not yet fully developed, so he chooses to retreat and seek guidance from someone who can help him understand and control his abilities."
            ]

            story_intro = """in the bustling city of Metroville, there lived an ordinary 17-year-old boy named Eric. \n
            Little did everyone know, Eric possessed extraordinary superpowers that he had yet to fully understand and master. \n
            From a young age, he had dreamed of becoming a superhero and using his abilities to protect the innocent and fight for justice. \n
            One sunny day, as Eric walked home from school, he noticed a commotion in the distance. Curiosity piqued, he hurried toward the source of the disturbance. \n
            To his surprise, he stumbled upon a bank robbery in progress.The robbers were armed and threatening the innocent bank employees and customers. \n
            Now faced with a pivotal moment, Eric had to make a choice. How would he use his burgeoning powers to confront the criminals and bring them to justice? \n"""

            story_end = "What path will Eric choose? The decision is yours to make. \n"

            st.session_state.story = st.session_state.story + story_intro + story_end

            with text_col:
                storyBox = st.write(st.session_state.story)

            for option in options:
                if option.startswith("Option 1"):
                    text_col.markdown(f"<span style='color: Thistle'>{option}</span>", unsafe_allow_html=True)
                elif option.startswith("Option 2"):
                    text_col.markdown(f"<span style='color: Thistle'>{option}</span>", unsafe_allow_html=True)
                elif option.startswith("Option 3"):
                    text_col.markdown(f"<span style='color: Thistle'>{option}</span>", unsafe_allow_html=True)
                elif option.startswith("Option 4"):
                    text_col.markdown(f"<span style='color: Thistle'>{option}</span>", unsafe_allow_html=True)
                elif option.startswith("Option 5"):
                    text_col.markdown(f"<span style='color: Thistle'>{option}</span>", unsafe_allow_html=True)

        n = 1
        if st.session_state.init:
            st.session_state.init = False
            prompt = """Heroic Transformation: Ordinary to Extraordinary, Symbolic Imagery, Justice Personified. 
            Depict the transformative journey of Eric, the 17-year-old with hidden superpowers, as he confronts the bank robbery. 
            Illustrate his evolution from an ordinary teenager to a symbol of justice and heroism.
            Utilize symbolic imagery to represent his newfound powers and the responsibilities that come with them. 
            Create a visually striking representation that inspires viewers and captures the essence of Eric's choice to become a superhero.""" ## populate w chatgpt img prompts
        generate_images(prompt, n, output_directory)
        file_path = os.path.join(output_directory, f"{prompt[:100]}{len(st.session_state.images)}.png")
        current_images= []
        for i in range(n):
            file_path = os.path.join(output_directory, f"{prompt[:100]}{len(st.session_state.images)}.png")
            st.session_state.captions.append(prompt)
            st.session_state.images.append(file_path)
            st.session_state.filenames.append(file_path)
        img_container.image(st.session_state.images, caption=st.session_state.captions)

    img_container.image(st.session_state.images, caption=st.session_state.captions)

if st.session_state.end:
    with text_col:
        storyBox = st.write(st.session_state.story)

Expected behavior:

To have the text appear like it does for the first paragraph below, but have line breaks. Same issue persists with st.markdown.

Actual behavior:

I cannot reproduce that running your code in streamlit 1.23.1. The code doesn’t run as is and I had to fill some gaps. That suggests that parts of the code you omitted might be relevant.

Sorry for the inconvenience, please try again with the updated code. I’m on Streamlit, version 1.24.0

Okay this is really weird, it works when I run the code above I will try to isolate the issue within my larger project.

I don’t understand what the issue is, I have a text and img col that I render separately could that be the issue?

Hard to tell but I don’t think so.

1 Like

I have attached a larger scope of the code snippet, hope that helps

Believe me, testing the code before posting it can save you a lot of time and effort.

Hi, sorry for wasting your time. I’ve found a solution. Adding a line break to both the start and end of the sentence seems to have done the trick, no more weird code boxes.

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