Pecximenes commited on
Commit
aecf0f2
·
verified ·
1 Parent(s): 686cd95

Update interface/app.py

Browse files
Files changed (1) hide show
  1. interface/app.py +31 -144
interface/app.py CHANGED
@@ -3,165 +3,52 @@ import streamlit.components.v1 as components
3
  import re
4
  import sys
5
  import os
6
- import requests
7
- from bs4 import BeautifulSoup
8
- import difflib
9
- from urllib.parse import urlparse, unquote
10
- from pipelines.message import send_message
11
- from agent import pipeline, knowledge, graph, graph_data
12
 
13
- # Configuração do caminho
14
  sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
15
 
16
- # Substitui o caminho do gráfico pelo conteúdo do graph_data
17
- graph = graph.replace('"../memory/graph_data.json"', f'{graph_data}')
18
 
19
- # Variáveis globais
20
- extracted_links = []
21
 
22
- # Configuração inicial do histórico de chat
23
- if "chat_history" not in st.session_state:
24
- st.session_state.chat_history = []
 
 
 
 
 
25
 
26
- # Funções utilitárias
27
- def extract_content(text, tag):
28
- """Extrai conteúdo de um texto com base na tag fornecida."""
29
- pattern = rf'<{tag}>(.*?)</{tag}>'
30
- match = re.search(pattern, text, re.DOTALL)
31
- return match.group(1).strip() if match else None
32
 
33
- def fetch_webpage_content(url):
34
- """Obtém o conteúdo HTML de uma URL e retorna o conteúdo principal."""
35
- try:
36
- response = requests.get(url)
37
- response.raise_for_status()
38
- soup = BeautifulSoup(response.text, 'html.parser')
39
- main_content = soup.find('div', id='main')
40
-
41
- if main_content:
42
- body_tag = soup.find('body')
43
- if body_tag:
44
- body_tag.clear()
45
- body_tag.append(main_content)
46
- return str(soup)
47
- return "<html><body><p>Could not find main content on the page.</p></body></html>"
48
- except requests.RequestException as e:
49
- return f"<html><body><p>Error fetching the webpage: {str(e)}</p></body></html>"
50
-
51
- def extract_links(html_content):
52
- """Extrai todos os links (URLs) de um conteúdo HTML."""
53
- soup = BeautifulSoup(html_content, 'html.parser')
54
- return [a_tag['href'] for a_tag in soup.find_all('a', href=True)]
55
-
56
- def url_to_suggestion(url):
57
- """Converte uma URL longa em uma sugestão amigável."""
58
- path = unquote(urlparse(url).path).strip('/').split('/')
59
- return path[-1].replace('-', ' ').replace('_', ' ').capitalize() if path else url
60
-
61
- def display_suggestions(links):
62
- """Exibe sugestões para o usuário com base nos links extraídos."""
63
- suggestions = [(link, url_to_suggestion(link)) for link in links if url_to_suggestion(link)]
64
- st.subheader("Sugestões de Passos:")
65
- if suggestions:
66
- st.write("Você também pode se interessar em:")
67
- for link, suggestion in suggestions:
68
- st.write(f"- {suggestion}")
69
  else:
70
- st.write("Não sugestões disponíveis no momento.")
71
-
72
-
73
- def navigate_page(full_url):
74
- """Função para navegar para uma nova página e atualizar o conteúdo."""
75
- global extracted_links
76
- with st.spinner("Obtendo conteúdo da página..."):
77
- content = fetch_webpage_content(full_url)
78
- extracted_links = extract_links(content)
79
- st.session_state.chat_history.append({"type": "page", "content": content, "links": extracted_links})
80
- st.subheader("Conteúdo da Página Web:")
81
- components.html(content, height=600, scrolling=True)
82
- display_suggestions(extracted_links)
83
- st.subheader("URL Completa:")
84
- st.write(full_url)
85
-
86
-
87
- def sidebar_content():
88
- st.image('https://www.gov.br/++theme++padrao_govbr/img/govbr-logo-large.png', width=200)
89
- st.header("Tópicos frequentes")
90
-
91
- # Botões de exemplo
92
- topics = [
93
- "Niveis da conta govbr.",
94
- "Dúvidas no reconhecimento facial.",
95
- "Dúvidas na autenticação dos bancos.",
96
- "Dúvidas para aumentar o nível com a cin."
97
- ]
98
-
99
- for topic in topics:
100
- st.button(topic)
101
-
102
- # Espaços em branco para organização
103
- for _ in range(5):
104
- st.write("")
105
-
106
- # Botão centralizado
107
- col1, col2, col3 = st.columns([1, 1, 1])
108
- with col2:
109
- st.button("VOLTAR")
110
 
111
- # Função para exibir mensagens de chat
112
- def display_chat():
113
- for msg in st.session_state.messages:
114
- st.chat_message(msg["role"]).write(msg["content"])
115
 
116
  def main():
117
- # Exibe o histórico do chat
118
- for message in st.session_state.chat_history:
119
- if message["type"] == "text":
120
- if "role" in message:
121
- if message["role"] == "user":
122
- st.chat_message("user").write(message["content"])
123
- else:
124
- st.chat_message("assistant").write(message["content"])
125
-
126
- elif message["type"] == "page":
127
- st.subheader("Conteúdo da Página Web:")
128
- components.html(message["content"], height=400, scrolling=True)
129
-
130
- if user_query := st.chat_input(placeholder="Digite sua mensagem"):
131
- # Armazenar mensagem do usuário
132
- st.session_state.chat_history.append({"type": "text","role": "user", "content": user_query})
133
- st.chat_message("user").write(user_query)
134
-
135
- response_text = send_message(user_query, pipeline)
136
-
137
- # Remover ou ocultar a tag <path> da resposta
138
- clean_response_text = re.sub(r'<path>(.*?)</path>', '', response_text).strip()
139
- # Armazena a resposta do agent sem a tag <path>
140
- st.session_state.chat_history.append({"type": "text", "role": "assistant", "content": clean_response_text})
141
- st.chat_message("assistant").write(clean_response_text)
142
-
143
- # Extração do caminho da resposta do bot
144
- path = extract_content(response_text, "path")
145
- if path:
146
- base_url = "https://www.gov.br/governodigital/pt-br/"
147
- full_url = base_url + path
148
- navigate_page(full_url)
149
-
150
-
151
 
152
- # Exibição da barra lateral
153
- with st.sidebar:
154
- sidebar_content()
155
 
156
- # Exibição do título e subtítulo
157
- st.title("Bem-vindo à ajuda do gov.br")
158
- st.caption("💬 Qual a sua dificuldade hoje? Estou aqui para ajudar!")
 
159
 
160
- # Configuração inicial
161
- if "messages" not in st.session_state:
162
- st.session_state["messages"] = [{"role": "assistant", "content": "Como eu posso ajudar?"}]
 
163
 
164
- display_chat()
165
 
166
  if __name__ == "__main__":
167
  main()
 
3
  import re
4
  import sys
5
  import os
 
 
 
 
 
 
6
 
7
+ # Configuração do caminho para incluir as pastas necessárias
8
  sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9
 
10
+ # Importando módulos necessários
11
+ from interface.chatbot import Chatbot
12
 
 
 
13
 
14
+ def display_message(message):
15
+ """Exibe a mensagem no chat, processando o tipo de mensagem."""
16
+ if message["type"] == "text":
17
+ # Remove a tag <path> da mensagem, se existir
18
+ response_without_path = re.sub(r'<path>(.*?)</path>', '', message["content"]).strip()
19
+ st.chat_message(message["role"]).write(response_without_path)
20
+ elif message["type"] == "page":
21
+ display_page_message(message)
22
 
 
 
 
 
 
 
23
 
24
+ def display_page_message(message):
25
+ """Exibe a mensagem de tipo 'page', lidando com possíveis erros."""
26
+ if "ERROR" in message["content"].upper():
27
+ st.chat_message(message["role"]).write("Infelizmente, não consegui entender. Você poderia perguntar de outra forma?")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  else:
29
+ st.subheader("Conteúdo da Página Web:")
30
+ height = 600 if message == st.session_state.chat_history[-1] else 400
31
+ components.html(message["content"], height=height, scrolling=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
 
 
 
 
33
 
34
  def main():
35
+ app = Chatbot()
36
+
37
+ with st.sidebar:
38
+ app.create_sidebar()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ app.mount_chatbot()
 
 
41
 
42
+ if app.response:
43
+ app.add_to_history(app.response, role="user")
44
+ app.generate_awnser(app.response)
45
+ app.response = "" # Zerando a variável após uso
46
 
47
+ for message in st.session_state.chat_history:
48
+ display_message(message)
49
+ if message["type"] == "page" and message == st.session_state.chat_history[-1]:
50
+ app.display_suggestions(app.links)
51
 
 
52
 
53
  if __name__ == "__main__":
54
  main()