Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import streamlit.components.v1 as components | |
| import re | |
| import sys | |
| import os | |
| import requests | |
| from bs4 import BeautifulSoup | |
| import difflib | |
| from urllib.parse import urlparse, unquote | |
| from pipelines.message import send_message | |
| from agent import pipeline, knowledge, graph, graph_data | |
| # Configuração do caminho | |
| sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| # Substitui o caminho do gráfico pelo conteúdo do graph_data | |
| graph = graph.replace('"../memory/graph_data.json"', f'{graph_data}') | |
| # Variáveis globais | |
| extracted_links = [] | |
| # Configuração inicial do histórico de chat | |
| if "chat_history" not in st.session_state: | |
| st.session_state.chat_history = [] | |
| # Funções utilitárias | |
| def extract_content(text, tag): | |
| """Extrai conteúdo de um texto com base na tag fornecida.""" | |
| pattern = rf'<{tag}>(.*?)</{tag}>' | |
| match = re.search(pattern, text, re.DOTALL) | |
| return match.group(1).strip() if match else None | |
| def fetch_webpage_content(url): | |
| """Obtém o conteúdo HTML de uma URL e retorna o conteúdo principal.""" | |
| try: | |
| response = requests.get(url) | |
| response.raise_for_status() | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| main_content = soup.find('div', id='main') | |
| if main_content: | |
| body_tag = soup.find('body') | |
| if body_tag: | |
| body_tag.clear() | |
| body_tag.append(main_content) | |
| return str(soup) | |
| return "<html><body><p>Could not find main content on the page.</p></body></html>" | |
| except requests.RequestException as e: | |
| return f"<html><body><p>Error fetching the webpage: {str(e)}</p></body></html>" | |
| def extract_links(html_content): | |
| """Extrai todos os links (URLs) de um conteúdo HTML.""" | |
| soup = BeautifulSoup(html_content, 'html.parser') | |
| return [a_tag['href'] for a_tag in soup.find_all('a', href=True)] | |
| def url_to_suggestion(url): | |
| """Converte uma URL longa em uma sugestão amigável.""" | |
| path = unquote(urlparse(url).path).strip('/').split('/') | |
| return path[-1].replace('-', ' ').replace('_', ' ').capitalize() if path else url | |
| def display_suggestions(links): | |
| """Exibe sugestões para o usuário com base nos links extraídos.""" | |
| suggestions = [(link, url_to_suggestion(link)) for link in links if url_to_suggestion(link)] | |
| st.subheader("Sugestões de Passos:") | |
| if suggestions: | |
| st.write("Você também pode se interessar em:") | |
| for link, suggestion in suggestions: | |
| st.write(f"- {suggestion}") | |
| else: | |
| st.write("Não há sugestões disponíveis no momento.") | |
| def navigate_page(full_url): | |
| """Função para navegar para uma nova página e atualizar o conteúdo.""" | |
| global extracted_links | |
| with st.spinner("Obtendo conteúdo da página..."): | |
| content = fetch_webpage_content(full_url) | |
| extracted_links = extract_links(content) | |
| st.session_state.chat_history.append({"type": "page", "content": content, "links": extracted_links}) | |
| st.subheader("Conteúdo da Página Web:") | |
| components.html(content, height=600, scrolling=True) | |
| display_suggestions(extracted_links) | |
| st.subheader("URL Completa:") | |
| st.write(full_url) | |
| def sidebar_content(): | |
| st.image('https://www.gov.br/++theme++padrao_govbr/img/govbr-logo-large.png', width=200) | |
| st.header("Tópicos frequentes") | |
| # Botões de exemplo | |
| topics = [ | |
| "Lorem ipsum dolor sit amet, consectetur adipiscing elit1.", | |
| "Lorem ipsum dolor sit amet, consectetur adipiscing elit2.", | |
| "Lorem ipsum dolor sit amet, consectetur adipiscing elit3.", | |
| "Lorem ipsum dolor sit amet, consectetur adipiscing elit4." | |
| ] | |
| for topic in topics: | |
| st.button(topic) | |
| # Espaços em branco para organização | |
| for _ in range(5): | |
| st.write("") | |
| # Botão centralizado | |
| col1, col2, col3 = st.columns([1, 1, 1]) | |
| with col2: | |
| st.button("VOLTAR") | |
| # Função para exibir mensagens de chat | |
| def display_chat(): | |
| for msg in st.session_state.messages: | |
| st.chat_message(msg["role"]).write(msg["content"]) | |
| def main(): | |
| # Exibe o histórico do chat | |
| for message in st.session_state.chat_history: | |
| if message["type"] == "text": | |
| if "role" in message: | |
| if message["role"] == "user": | |
| st.chat_message("user").write(message["content"]) | |
| else: | |
| st.chat_message("assistant").write(message["content"]) | |
| elif message["type"] == "page": | |
| st.subheader("Conteúdo da Página Web:") | |
| components.html(message["content"], height=400, scrolling=True) | |
| if user_query := st.chat_input(placeholder="Digite sua mensagem"): | |
| # Armazenar mensagem do usuário | |
| st.session_state.chat_history.append({"type": "text","role": "user", "content": user_query}) | |
| st.chat_message("user").write(user_query) | |
| response_text = send_message(user_query, pipeline) | |
| # Armazena a resposta do agent | |
| st.session_state.chat_history.append({"type": "text","role": "assistant", "content": response_text}) | |
| st.chat_message("assistant").write(response_text) | |
| # Extração do caminho da resposta do bot | |
| path = extract_content(response_text, "path") | |
| if path: | |
| base_url = "https://www.gov.br/governodigital/pt-br/" | |
| full_url = base_url + path | |
| navigate_page(full_url) | |
| # Exibição da barra lateral | |
| with st.sidebar: | |
| sidebar_content() | |
| # Exibição do título e subtítulo | |
| st.title("Bem-vindo à ajuda do gov.br") | |
| st.caption("💬 Qual a sua dificuldade hoje? Estou aqui para ajudar!") | |
| # Configuração inicial | |
| if "messages" not in st.session_state: | |
| st.session_state["messages"] = [{"role": "assistant", "content": "Como eu posso ajudar?"}] | |
| display_chat() | |
| if __name__ == "__main__": | |
| main() | |