Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| from streamlit.components.v1 import components | |
| import json | |
| from dataclasses import dataclass | |
| from typing import Literal | |
| from utils import Agent | |
| agent = Agent() | |
| class Message: | |
| origin: Literal["human", "ai"] | |
| message: str | |
| confidence:int | |
| def load_css(): | |
| with open('./static/style.css') as fp: | |
| css = f"<style>{fp.read()}</style>" | |
| st.markdown(css, unsafe_allow_html=True) | |
| def initialize_session_state(): | |
| if "history" not in st.session_state: | |
| st.session_state.history = [] | |
| def on_click_call_back(): | |
| human_prompt = st.session_state.human_prompt | |
| agent_response, confidence = agent.agent_response(human_prompt) | |
| st.session_state.history.append(Message(origin='human', message=human_prompt, confidence=None)) | |
| st.session_state.history.append(Message(origin='ai', message=agent_response, confidence=confidence)) | |
| st.title("Shopping agent Demo 🤖") | |
| load_css() | |
| initialize_session_state() | |
| chat_placeholder = st.container() | |
| prompt_placeholder = st.form(key="chat-form ") | |
| with chat_placeholder: | |
| for chat in st.session_state.history: | |
| msg = f"""<div class='chat-row {'chat-row-reverse' if chat.origin == 'human' else None }'> | |
| <img class='chat-row--img' src='app/static/{'boy.png' if chat.origin=='human' else 'robot.png'}' /> | |
| <div class='chat-row--msg {'chat-row--user' if chat.origin=='human' else 'chat-row--ai'}'>{chat.message}{f'<span class="chat-row--confidence"><span>CONFIDENCE : </span><span>{chat.confidence*100 :0.2f}%</span></span>' if chat.confidence else ''}</div> | |
| </div>""" | |
| st.markdown(msg, unsafe_allow_html=True) | |
| with prompt_placeholder: | |
| cols_1, cols_2 = st.columns((6,1)) | |
| with cols_1: | |
| st.text_input(label="Chat", value="Hello bot", label_visibility="collapsed", key="human_prompt") | |
| with cols_2: | |
| st.form_submit_button(label="Submit", type="primary", on_click=on_click_call_back) | |
| # components.html(""" | |
| # <script> | |
| # const streamlitDoc = window.parent.document; | |
| # const buttons = Array.from( | |
| # streamlitDoc.querySelectorAll('.stButton > button') | |
| # ); | |
| # const submitButton = buttons.find( | |
| # el => el.innerText === 'Submit' | |
| # ); | |
| # streamlitDoc.addEventListener('keydown', function(e) { | |
| # switch (e.key) { | |
| # case 'Enter': | |
| # submitButton.click(); | |
| # break; | |
| # } | |
| # }); | |
| # </script> | |
| # """, | |
| # height=0, | |
| # width=0, | |
| # ) |