Я перебираю источники/ссылки своих данных и хочу отображать их построчно. Каким-то образом правильно отображается только первая строка, остальные строки отображаются в виде блоков кода в потоке света. Понятия не имею, почему.
Это мой результат:
[img]https:// i.sstatic.net/gBh3aSIz.png[/img]
from dataclasses import dataclass
from typing import List, Literal, Optional
import streamlit as st
from PIL import Image
from backend.generate_answer_lambda import get_answer
from backend.get_sources_lambda import get_sources
import time
import re
# Ensure CSS file path is correct
CSS_FILE_PATH = "static/styles/styles.css"
st.set_page_config(
page_icon=Image.open('static/images/mhp_fav_icon.png'),
layout="wide",
initial_sidebar_state="expanded",
)
@dataclass
class Message:
"""Class for keeping track of a chat message."""
origin: Literal["human", "ai"]
message: str
sources: Optional[List[dict]] = None
# Read the CSS file and ensure it's loaded properly
with open(CSS_FILE_PATH, "r") as f:
css = f.read()
# Append version query parameter to avoid caching issues
version = time.time() # Current time to ensure a new version each time
st.markdown(f'{css}', unsafe_allow_html=True)
def initialize_session_state():
if "chat_history" not in st.session_state:
st.session_state.chat_history = [
Message(origin="ai", message="Hello, How can I help you today?")
]
if "sources" not in st.session_state:
st.session_state.sources = get_sources()
initialize_session_state()
def stream_response(answer):
pattern = re.compile(r'(\s+|\W+)', re.UNICODE)
chunks = pattern.split(answer)
for chunk in chunks:
yield chunk
time.sleep(0.03)
def on_user_input(user_query):
st.session_state.chat_history.append(Message(origin="human", message=user_query))
chat_placeholder.markdown(f"""
[img]app/static/images/user_icon.png[/img]
{user_query}
""", unsafe_allow_html=True)
response_placeholder = chat_placeholder.empty()
expander_placeholder = st.empty()
with response_placeholder:
st.markdown(f"""
[img]app/static/images/ai_icon.png[/img]
""", unsafe_allow_html=True)
# Fetch the answer
answer, sources = get_answer(user_query)
# Once answer is fetched, hide the spinner and display the response
st.empty() # Remove the spinner
# Stream the response
streamed_response = ""
for chunk in stream_response(answer):
streamed_response += chunk
response_placeholder.markdown(f"""
[img]app/static/images/ai_icon.png[/img]
{streamed_response}
""", unsafe_allow_html=True)
if sources:
with expander_placeholder.expander(label="References"):
html_content = ""
for idx, source in enumerate(sources):
html_content += f"""
{idx + 1}
[url={source[]{source['filename']}[/url]
{''.join([f"{page}" for page in source['pages']])}
"""
if idx == len(sources) - 1:
html_content += ""
print(html_content)
st.markdown(html_content, unsafe_allow_html=True)
else:
st.sidebar.warning("No References found.")
st.session_state.chat_history.append(Message(origin="ai", message=streamed_response, sources=sources))
st.markdown("""
MHP Chatbot
""", unsafe_allow_html=True)
chat_placeholder = st.container()
st.sidebar.image('static/images/mhp_sidebar_logo.png', width=180)
st.sidebar.markdown("#")
with chat_placeholder:
st.markdown("#")
for chat in st.session_state.chat_history:
if chat.origin == "ai":
st.markdown(f"""
[img]app/static/images/ai_icon.png[/img]
{chat.message}
""", unsafe_allow_html=True)
# Check if sources exist for this AI response
if chat.sources:
expander_placeholder = st.empty()
with expander_placeholder.expander(label="References"):
html_content = ""
for idx, source in enumerate(chat.sources):
html_content += f"""
{idx + 1}
[url={source[]{source['filename']}[/url]
{''.join([f"{page}" for page in source['pages']])}
"""
if idx == len(chat.sources) - 1:
html_content += ""
print(f"in loop {html_content}")
st.markdown(html_content, unsafe_allow_html=True)
else:
st.markdown(f"""
[img]app/static/images/user_icon.png[/img]
{chat.message}
""", unsafe_allow_html=True)
user_query = st.chat_input("Your message")
if user_query:
on_user_input(user_query)
uploaded_file = st.sidebar.file_uploader("Upload PDF file")
# if uploaded_file is not None:
# upload_file(uploaded_file)
sources = st.session_state.sources
st.sidebar.markdown("")
# Check if sources exist
if sources:
with st.sidebar.expander(label="PDF Files"):
for source in sources:
st.page_link(source['url'], label=source["filename"], icon='📄')
else:
st.sidebar.warning("No PDF files found.")
Я перебираю источники/ссылки своих данных и хочу отображать их построчно. Каким-то образом правильно отображается только первая строка, остальные строки отображаются в виде блоков кода в потоке света. Понятия не имею, почему. Это мой результат: [img]https:// i.sstatic.net/gBh3aSIz.png[/img]
[/code] Это мое приложение с потоковой подсветкой: [code]from dataclasses import dataclass from typing import List, Literal, Optional import streamlit as st from PIL import Image from backend.generate_answer_lambda import get_answer from backend.get_sources_lambda import get_sources import time import re
# Ensure CSS file path is correct CSS_FILE_PATH = "static/styles/styles.css"
@dataclass class Message: """Class for keeping track of a chat message.""" origin: Literal["human", "ai"] message: str sources: Optional[List[dict]] = None
# Read the CSS file and ensure it's loaded properly with open(CSS_FILE_PATH, "r") as f: css = f.read() # Append version query parameter to avoid caching issues version = time.time() # Current time to ensure a new version each time st.markdown(f'{css}', unsafe_allow_html=True)
def initialize_session_state(): if "chat_history" not in st.session_state: st.session_state.chat_history = [ Message(origin="ai", message="Hello, How can I help you today?") ]
if "sources" not in st.session_state: st.session_state.sources = get_sources()
initialize_session_state()
def stream_response(answer): pattern = re.compile(r'(\s+|\W+)', re.UNICODE) chunks = pattern.split(answer) for chunk in chunks: yield chunk time.sleep(0.03)
""", unsafe_allow_html=True) # Check if sources exist for this AI response if chat.sources: expander_placeholder = st.empty() with expander_placeholder.expander(label="References"): html_content = "" for idx, source in enumerate(chat.sources): html_content += f"""
{idx + 1} [url={source[]{source['filename']}[/url] {''.join([f"{page}" for page in source['pages']])}
user_query = st.chat_input("Your message") if user_query: on_user_input(user_query)
uploaded_file = st.sidebar.file_uploader("Upload PDF file")
# if uploaded_file is not None: # upload_file(uploaded_file)
sources = st.session_state.sources st.sidebar.markdown("") # Check if sources exist if sources: with st.sidebar.expander(label="PDF Files"): for source in sources: st.page_link(source['url'], label=source["filename"], icon='📄') else: st.sidebar.warning("No PDF files found.")
[/code] Это мой CSS: [code]@import url("https://fonts.googleapis.com/css2?family=Orbitron:wght@400..900&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap");