Spaces:
Sleeping
Sleeping
import streamlit as st | |
import streamlit.components.v1 as components | |
import re | |
import sys | |
import os | |
from dotenv import load_dotenv | |
from openai import OpenAI | |
# Configuração do caminho para incluir as pastas necessárias | |
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
load_dotenv(override=True) | |
# Importando módulos necessários | |
from interface.chatbot import Chatbot | |
from interface.login import Login | |
from interface.postgres import Postgres | |
def connect_to_services(): | |
oa_client = OpenAI( | |
api_key=os.environ.get("OPENAI_API_KEY") | |
) | |
postgres_client = Postgres( | |
host=os.environ.get("DB_HOST"), | |
database=os.environ.get("DB_NAME"), | |
user=os.environ.get("DB_USER"), | |
password=os.environ.get("DB_PASSWORD"), | |
) | |
return oa_client, postgres_client | |
def display_message(message): | |
"""Exibe a mensagem no chat, processando o tipo de mensagem.""" | |
if message["type"] == "text": | |
# Remove a tag <path> da mensagem, se existir | |
response_without_path = re.sub(r'<path>(.*?)</path>', '', message["content"]).strip() | |
st.chat_message(message["role"]).write(response_without_path) | |
elif message["type"] == "page": | |
display_page_message(message) | |
def display_page_message(message): | |
"""Exibe a mensagem de tipo 'page', lidando com possíveis erros.""" | |
if "ERROR" in message["content"].upper(): | |
st.chat_message(message["role"]).write("Esta informação não está em meu alcance.") | |
else: | |
st.subheader("Conteúdo da Página Web:") | |
height = 600 if message == st.session_state.chat_history[-1] else 400 | |
components.html(message["content"], height=height, scrolling=True) | |
def main(): | |
if "services" not in st.session_state: | |
oa_client, postgres_client = connect_to_services() | |
st.session_state.services = { | |
"oa_client": oa_client, | |
"postgres_client": postgres_client | |
} | |
login = Login() | |
app = Chatbot() | |
if not st.session_state.user_authorized: | |
login.mount_login_page() | |
else: | |
with st.sidebar: | |
app.create_sidebar() # Corrigido para chamar o método que cria o sidebar | |
app.mount_chatbot() # Recebe o input de texto feito pelo usuário | |
if app.response: | |
app.add_to_history(app.response, role="user") | |
app.generate_answer(app.response) | |
app.response = "" # Zerando a variável após uso | |
st.session_state.is_feedback_active = True # Ativando o feedback | |
for message in st.session_state.chat_history: | |
display_message(message) | |
if message["type"] == "page" and message == st.session_state.chat_history[-1]: | |
app.display_suggestions(app.links) | |
if st.session_state.is_feedback_active: | |
app.display_feedback() | |
if __name__ == "__main__": | |
main() | |