File size: 4,933 Bytes
b7835d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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 display_knowledge_tree(structure):
    """Exibe a estrutura de conhecimento na barra lateral do Streamlit."""
    with st.sidebar.expander("Knowledge Structure", expanded=True):
        components.html(graph, height=600, scrolling=True)
        st.markdown(structure)

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 main():
    st.title("Alfred - Assistente de IA para Serviços gov.br")
    st.write("Qual a sua dificuldade hoje? Estou aqui para ajudar!")
    display_knowledge_tree(knowledge)

    # Exibe o histórico do chat
    for message in st.session_state.chat_history:
        if message["type"] == "text":
            st.markdown(message["content"])
        elif message["type"] == "page":
            st.subheader("Conteúdo da Página Web:")
            components.html(message["content"], height=400, scrolling=True)

    with st.form(key='user_input_form', clear_on_submit=True):
        user_query = st.text_input("Digite sua mensagem aqui:")
        submit_button = st.form_submit_button(label='Enviar')
        if submit_button and user_query:
            response_text = send_message(user_query, pipeline)
            st.write("Bot:", response_text)
            st.session_state.chat_history.append({"type": "text", "content": f"**Você:** {user_query}"})
            
            # 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)
            
            st.session_state.chat_history.append({"type": "text", "content": f"**Bot:** {response_text}"})

if __name__ == "__main__":
    main()