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

Upload aux_functions and chatbot object to interface

Browse files
interface/auxiliary_functions.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Funções utilitárias
2
+ import re
3
+ import requests
4
+ from bs4 import BeautifulSoup
5
+ from urllib.parse import urlparse, unquote
6
+
7
+
8
+ def extract_content(text, tag):
9
+ """Extrai conteúdo de um texto com base na tag fornecida."""
10
+ pattern = rf'<{tag}>(.*?)</{tag}>'
11
+ match = re.search(pattern, text, re.DOTALL)
12
+ return match.group(1).strip() if match else None
13
+
14
+ def fetch_webpage_content(url):
15
+ """Obtém o conteúdo HTML de uma URL e retorna o conteúdo principal."""
16
+ try:
17
+ response = requests.get(url)
18
+ response.raise_for_status()
19
+ soup = BeautifulSoup(response.text, 'html.parser')
20
+ main_content = soup.find('div', id='main')
21
+
22
+ if main_content:
23
+ body_tag = soup.find('body')
24
+ if body_tag:
25
+ body_tag.clear()
26
+ body_tag.append(main_content)
27
+ return str(soup)
28
+ return "<html><body><p>Could not find main content on the page.</p></body></html>"
29
+ except requests.RequestException as e:
30
+ return f"<html><body><p>Error fetching the webpage: {str(e)}</p></body></html>"
31
+
32
+ def extract_links(html_content):
33
+ """Extrai todos os links (URLs) de um conteúdo HTML."""
34
+ soup = BeautifulSoup(html_content, 'html.parser')
35
+ return [a_tag['href'] for a_tag in soup.find_all('a', href=True)]
36
+
37
+ def url_to_suggestion(url):
38
+ """Converte uma URL longa em uma sugestão amigável."""
39
+ path = unquote(urlparse(url).path).strip('/').split('/')
40
+ return path[-1].replace('-', ' ').replace('_', ' ').capitalize() if path else url
interface/chatbot.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import sys
3
+ import os
4
+
5
+ # Configuração do caminho para incluir as pastas necessárias
6
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
7
+
8
+ from pipelines.message import send_message
9
+ from agent import pipeline
10
+ from interface.auxiliary_functions import (
11
+ extract_content,
12
+ extract_links,
13
+ fetch_webpage_content,
14
+ url_to_suggestion
15
+ )
16
+
17
+
18
+ class Chatbot():
19
+ def __init__(self):
20
+ # Configuração inicial do histórico de chat
21
+ if "chat_history" not in st.session_state:
22
+ st.session_state.chat_history = [{
23
+ "type": "text",
24
+ "role": "assistant",
25
+ "content": "Como eu posso ajudar?",
26
+ "links": []
27
+ }]
28
+
29
+ # Conteúdo dos botões do sidebar
30
+ if "topics" not in st.session_state:
31
+ st.session_state["topics"] = [
32
+ "Niveis da conta govbr.",
33
+ "Dúvidas no reconhecimento facial.",
34
+ "Como recuperar minha conta gov.br",
35
+ "Dúvidas para aumentar o nível com a cin."
36
+ ]
37
+
38
+ # Pergunta do usuário no chatbot
39
+ self.response = ""
40
+ self.links = []
41
+
42
+
43
+ def display_suggestions(self, links):
44
+ suggestions = [(link, url_to_suggestion(link)) for link in links if url_to_suggestion(link)]
45
+ st.subheader("Sugestões de Passos:")
46
+ if suggestions:
47
+ st.write("Você também pode se interessar em:")
48
+ for link, suggestion in suggestions:
49
+ st.write(f"- {suggestion}")
50
+ else:
51
+ st.write("Não há sugestões disponíveis no momento.")
52
+
53
+
54
+ def mount_chatbot(self):
55
+ # Exibição do título e subtítulo
56
+ st.title("Bem-vindo à ajuda do gov.br")
57
+ st.caption("💬 Qual a sua dificuldade hoje? Estou aqui para ajudar!")
58
+
59
+ # Exibição do espaço para mandar mensagem
60
+ if user_query := st.chat_input(placeholder="Digite sua mensagem"):
61
+ st.session_state.chat_history.append({"type": "text","role": "user", "content": user_query})
62
+
63
+ #TODO Aplicar o llm_rag nessa parte
64
+ full_link = self.generate_awnser(user_query)
65
+
66
+
67
+ def create_sidebar(self):
68
+ st.image('https://www.gov.br/++theme++padrao_govbr/img/govbr-logo-large.png', width=200)
69
+ st.header("Tópicos frequentes")
70
+
71
+ for topic in st.session_state.topics:
72
+ if st.button(topic, key=topic):
73
+ self.response = topic
74
+
75
+
76
+ # Espaços em branco para organização
77
+ for _ in range(5):
78
+ st.write("")
79
+
80
+ # Botão centralizado
81
+ col1, col2, col3 = st.columns([1, 2, 1])
82
+ with col2:
83
+ if st.button("LIMPAR HISTÓRICO"):
84
+ st.session_state.chat_history = [{
85
+ "type": "text",
86
+ "role": "assistant",
87
+ "content": "Como eu posso ajudar?",
88
+ "links": []
89
+ }]
90
+
91
+
92
+ def add_to_history(self, message, role="user", type="text"):
93
+ st.session_state.chat_history.append({
94
+ "role": role,
95
+ "type": type,
96
+ "content": message
97
+ })
98
+
99
+
100
+ def generate_awnser(self, input_message):
101
+ # Retorna o caminho do site gov que responde a pergunta
102
+ response_text = send_message(input_message, pipeline)
103
+
104
+ # Armazena a resposta do agent com a tag <path>
105
+ self.add_to_history(response_text, role="assistant")
106
+
107
+ # Extração do caminho da resposta do bot
108
+ path = extract_content(response_text, "path")
109
+ if path:
110
+ base_url = "https://www.gov.br/governodigital/pt-br/"
111
+ full_url = base_url + path
112
+ with st.spinner("Obtendo conteúdo da página..."):
113
+ content = fetch_webpage_content(full_url)
114
+
115
+ self.add_to_history(content, role="assistant", type="page")
116
+
117
+
118
+ extracted_links = extract_links(content)
119
+ self.links = extracted_links