Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -8,221 +8,184 @@ import random
|
|
8 |
import hashlib
|
9 |
from datetime import datetime
|
10 |
|
11 |
-
logging
|
|
|
|
|
|
|
|
|
12 |
logger = logging.getLogger(__name__)
|
13 |
warnings.filterwarnings('ignore')
|
14 |
|
15 |
-
#
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
-
def
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
-
# Temas
|
22 |
-
|
23 |
-
"casamento": "💑 Casamento
|
24 |
-
"criacao_filhos": "👶 Criação de Filhos"
|
25 |
-
"papel_mulher": "👩 Papel da Mulher",
|
26 |
-
"papel_homem": "👨 Papel do Homem",
|
27 |
-
"financas": "💰 Finanças",
|
28 |
-
"trabalho": "💼 Trabalho"
|
29 |
}
|
30 |
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
background-color: #f8f9fa;
|
44 |
-
padding: 15px;
|
45 |
-
border-radius: 10px;
|
46 |
-
margin: 10px 0;
|
47 |
-
}
|
48 |
-
.theme-selector {
|
49 |
-
margin-bottom: 20px;
|
50 |
-
}
|
51 |
-
"""
|
52 |
-
|
53 |
-
with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:
|
54 |
-
# Cabeçalho
|
55 |
-
with gr.Row(elem_classes="container"):
|
56 |
-
gr.Markdown("""
|
57 |
-
# 🕊️ Conselheiro Bíblico Virtual
|
58 |
-
### Orientação Espiritual Baseada nas Sagradas Escrituras
|
59 |
-
|
60 |
-
_"Toda a Escritura é inspirada por Deus e útil para o ensino, para a repreensão,
|
61 |
-
para a correção e para a instrução na justiça." - 2 Timóteo 3:16_
|
62 |
-
""")
|
63 |
-
|
64 |
-
# Conteúdo Principal
|
65 |
-
with gr.Tabs() as tabs:
|
66 |
-
# Aba de Aconselhamento
|
67 |
-
with gr.TabItem("📚 Aconselhamento", id=1):
|
68 |
-
with gr.Row():
|
69 |
-
# Coluna Esquerda - Entrada
|
70 |
-
with gr.Column(scale=1):
|
71 |
-
theme = gr.Dropdown(
|
72 |
-
choices=list(THEMES.items()),
|
73 |
-
label="Escolha o Tema",
|
74 |
-
value="casamento",
|
75 |
-
elem_classes="theme-selector"
|
76 |
-
)
|
77 |
-
|
78 |
-
# Versículo do Dia
|
79 |
-
verse_box = gr.Textbox(
|
80 |
-
label="✨ Versículo do Dia",
|
81 |
-
value="Renovado diariamente...",
|
82 |
-
elem_classes="verse-box",
|
83 |
-
lines=3,
|
84 |
-
interactive=False
|
85 |
-
)
|
86 |
-
|
87 |
-
question = gr.Textbox(
|
88 |
-
label="💭 Sua Pergunta",
|
89 |
-
placeholder="Digite sua dúvida ou preocupação...",
|
90 |
-
lines=3
|
91 |
-
)
|
92 |
-
|
93 |
-
with gr.Row():
|
94 |
-
submit_btn = gr.Button("🙏 Buscar Orientação", variant="primary")
|
95 |
-
clear_btn = gr.Button("🔄 Nova Consulta")
|
96 |
-
|
97 |
-
# Coluna Direita - Saída
|
98 |
-
with gr.Column(scale=1):
|
99 |
-
with gr.Box():
|
100 |
-
answer_output = gr.Markdown(
|
101 |
-
label="Resposta",
|
102 |
-
value="Sua orientação aparecerá aqui..."
|
103 |
-
)
|
104 |
-
|
105 |
-
with gr.Accordion("📖 Referências Bíblicas", open=False):
|
106 |
-
references = gr.Markdown()
|
107 |
-
|
108 |
-
# Feedback
|
109 |
-
with gr.Row():
|
110 |
-
gr.Markdown("Esta resposta foi útil?")
|
111 |
-
helpful_btn = gr.Button("👍", elem_classes="feedback-btn")
|
112 |
-
not_helpful_btn = gr.Button("👎", elem_classes="feedback-btn")
|
113 |
-
|
114 |
-
# Aba de Exemplos
|
115 |
-
with gr.TabItem("📋 Exemplos", id=2):
|
116 |
-
gr.Examples(
|
117 |
-
examples=[
|
118 |
-
["casamento", "Como resolver conflitos no casamento?"],
|
119 |
-
["casamento", "Como manter um casamento forte espiritualmente?"],
|
120 |
-
["casamento", "Qual o papel do perdão no casamento?"],
|
121 |
-
["casamento", "Como manter a fidelidade no casamento?"],
|
122 |
-
["casamento", "Como lidar com diferenças no casamento?"]
|
123 |
-
],
|
124 |
-
inputs=[theme, question],
|
125 |
-
outputs=[answer_output, references],
|
126 |
-
fn=lambda t, q: counselor.get_unique_response(q, t),
|
127 |
-
label="Exemplos de Perguntas Comuns"
|
128 |
)
|
129 |
-
|
130 |
-
# Aba de Recursos
|
131 |
-
with gr.TabItem("📚 Recursos", id=3):
|
132 |
-
gr.Markdown("""
|
133 |
-
### 📖 Recursos Disponíveis
|
134 |
-
|
135 |
-
#### Temas Abordados:
|
136 |
-
- 💑 **Casamento e Família**
|
137 |
-
- Relacionamento conjugal
|
138 |
-
- Comunicação
|
139 |
-
- Resolução de conflitos
|
140 |
-
|
141 |
-
- 👶 **Criação de Filhos**
|
142 |
-
- Educação cristã
|
143 |
-
- Disciplina
|
144 |
-
- Desenvolvimento espiritual
|
145 |
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
- 👨 **Papel do Homem**
|
152 |
-
- Liderança espiritual
|
153 |
-
- Responsabilidades
|
154 |
-
- Paternidade
|
155 |
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
5. Use o feedback para nos ajudar a melhorar
|
162 |
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
|
178 |
# Eventos
|
179 |
def clear_outputs():
|
180 |
-
return
|
181 |
-
question: "",
|
182 |
-
answer_output: "Sua orientação aparecerá aqui...",
|
183 |
-
references: ""
|
184 |
-
}
|
185 |
-
|
186 |
-
def update_verse():
|
187 |
-
verses = [
|
188 |
-
"O Senhor é meu pastor, nada me faltará. (Salmos 23:1)",
|
189 |
-
"Tudo posso naquele que me fortalece. (Filipenses 4:13)",
|
190 |
-
"O amor é paciente, o amor é bondoso... (1 Coríntios 13:4)"
|
191 |
-
]
|
192 |
-
return random.choice(verses)
|
193 |
-
|
194 |
-
def process_feedback(helpful: bool):
|
195 |
-
feedback_msg = "Obrigado pelo seu feedback! 🙏"
|
196 |
-
return gr.Markdown.update(value=feedback_msg)
|
197 |
|
198 |
-
# Eventos
|
199 |
submit_btn.click(
|
200 |
-
fn=
|
201 |
inputs=[theme, question],
|
202 |
outputs=[answer_output, references]
|
203 |
)
|
204 |
-
|
205 |
clear_btn.click(
|
206 |
fn=clear_outputs,
|
207 |
inputs=[],
|
208 |
outputs=[question, answer_output, references]
|
209 |
)
|
210 |
-
|
211 |
-
|
212 |
-
fn=lambda: process_feedback(True),
|
213 |
-
inputs=[],
|
214 |
-
outputs=[answer_output]
|
215 |
-
)
|
216 |
-
|
217 |
-
not_helpful_btn.click(
|
218 |
-
fn=lambda: process_feedback(False),
|
219 |
-
inputs=[],
|
220 |
-
outputs=[answer_output]
|
221 |
-
)
|
222 |
-
|
223 |
-
# Atualiza versículo do dia ao iniciar
|
224 |
demo.load(
|
225 |
-
fn=
|
226 |
inputs=[],
|
227 |
outputs=[verse_box]
|
228 |
)
|
@@ -231,8 +194,8 @@ def create_enhanced_interface():
|
|
231 |
|
232 |
if __name__ == "__main__":
|
233 |
try:
|
234 |
-
logger.info("Iniciando aplicação
|
235 |
-
demo =
|
236 |
demo.launch(
|
237 |
server_name="0.0.0.0",
|
238 |
share=True,
|
|
|
8 |
import hashlib
|
9 |
from datetime import datetime
|
10 |
|
11 |
+
# Configuração de logging
|
12 |
+
logging.basicConfig(
|
13 |
+
level=logging.INFO,
|
14 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
15 |
+
)
|
16 |
logger = logging.getLogger(__name__)
|
17 |
warnings.filterwarnings('ignore')
|
18 |
|
19 |
+
# Banco de passagens bíblicas
|
20 |
+
BIBLICAL_PASSAGES = {
|
21 |
+
"casamento": [
|
22 |
+
{
|
23 |
+
"passagem": "Efésios 5:22-33",
|
24 |
+
"texto": """Vós, mulheres, sujeitai-vos a vossos maridos, como ao Senhor; Porque o marido é a cabeça da mulher, como também Cristo é a cabeça da igreja... Assim devem os maridos amar as suas mulheres, como a seus próprios corpos.""",
|
25 |
+
"contexto": "Relacionamento conjugal",
|
26 |
+
"resposta_base": "O casamento cristão é baseado no amor sacrificial e no respeito mútuo, refletindo a relação entre Cristo e a Igreja."
|
27 |
+
}
|
28 |
+
],
|
29 |
+
"criacao_filhos": [
|
30 |
+
{
|
31 |
+
"passagem": "Provérbios 22:6",
|
32 |
+
"texto": "Instrui o menino no caminho em que deve andar, e até quando envelhecer não se desviará dele.",
|
33 |
+
"contexto": "Educação dos filhos",
|
34 |
+
"resposta_base": "A educação dos filhos deve ser fundamentada nos princípios bíblicos, com instrução constante e exemplo."
|
35 |
+
}
|
36 |
+
]
|
37 |
+
}
|
38 |
+
|
39 |
+
class BiblicalCounselor:
|
40 |
+
def __init__(self):
|
41 |
+
logger.info("Inicializando conselheiro bíblico...")
|
42 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
43 |
+
self.model_name = "pierreguillou/bert-base-cased-squad-v1.1-portuguese"
|
44 |
+
|
45 |
+
try:
|
46 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
|
47 |
+
self.model = AutoModelForQuestionAnswering.from_pretrained(self.model_name)
|
48 |
+
self.model.to(self.device)
|
49 |
+
logger.info(f"Modelo carregado com sucesso no dispositivo: {self.device}")
|
50 |
+
except Exception as e:
|
51 |
+
logger.error(f"Erro ao carregar modelo: {str(e)}")
|
52 |
+
raise
|
53 |
+
|
54 |
+
def get_answer(self, theme: str, question: str) -> Tuple[str, str]:
|
55 |
+
try:
|
56 |
+
if theme not in BIBLICAL_PASSAGES:
|
57 |
+
return "Tema não encontrado.", "Sem referências disponíveis."
|
58 |
+
|
59 |
+
passage = BIBLICAL_PASSAGES[theme][0]
|
60 |
+
context = passage["texto"]
|
61 |
+
|
62 |
+
inputs = self.tokenizer.encode_plus(
|
63 |
+
question,
|
64 |
+
context,
|
65 |
+
return_tensors="pt",
|
66 |
+
max_length=512,
|
67 |
+
truncation=True,
|
68 |
+
padding="max_length"
|
69 |
+
).to(self.device)
|
70 |
+
|
71 |
+
with torch.no_grad():
|
72 |
+
outputs = self.model(**inputs)
|
73 |
+
|
74 |
+
answer_start = torch.argmax(outputs.start_logits)
|
75 |
+
answer_end = torch.argmax(outputs.end_logits)
|
76 |
+
|
77 |
+
tokens = self.tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
|
78 |
+
answer = tokens[answer_start:answer_end + 1]
|
79 |
+
answer = self.tokenizer.convert_tokens_to_string(answer)
|
80 |
+
|
81 |
+
# Formata a resposta
|
82 |
+
response = f"""
|
83 |
+
🕊️ Orientação Bíblica:
|
84 |
+
{passage['resposta_base']}
|
85 |
+
|
86 |
+
📖 Baseado em {passage['passagem']}:
|
87 |
+
{answer}
|
88 |
+
|
89 |
+
✝️ Contexto:
|
90 |
+
{passage['contexto']}
|
91 |
+
"""
|
92 |
+
|
93 |
+
references = f"📚 Referência: {passage['passagem']}\n🔍 Contexto: {passage['contexto']}"
|
94 |
+
|
95 |
+
return response, references
|
96 |
+
|
97 |
+
except Exception as e:
|
98 |
+
logger.error(f"Erro ao processar pergunta: {str(e)}")
|
99 |
+
return "Ocorreu um erro ao processar sua pergunta.", "Erro no processamento"
|
100 |
|
101 |
+
def get_daily_verse() -> str:
|
102 |
+
"""Retorna um versículo diário"""
|
103 |
+
verses = [
|
104 |
+
"O Senhor é meu pastor, nada me faltará. (Salmos 23:1)",
|
105 |
+
"Tudo posso naquele que me fortalece. (Filipenses 4:13)",
|
106 |
+
"O amor é paciente, o amor é bondoso... (1 Coríntios 13:4)"
|
107 |
+
]
|
108 |
+
return random.choice(verses)
|
109 |
+
|
110 |
+
def create_interface():
|
111 |
+
counselor = BiblicalCounselor()
|
112 |
|
113 |
+
# Temas com ícones
|
114 |
+
themes = {
|
115 |
+
"casamento": "💑 Casamento",
|
116 |
+
"criacao_filhos": "👶 Criação de Filhos"
|
|
|
|
|
|
|
|
|
117 |
}
|
118 |
|
119 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
120 |
+
gr.Markdown("""
|
121 |
+
# 🕊️ Conselheiro Bíblico Virtual
|
122 |
+
### Orientação Espiritual Baseada nas Sagradas Escrituras
|
123 |
+
""")
|
124 |
+
|
125 |
+
with gr.Row():
|
126 |
+
with gr.Column():
|
127 |
+
theme = gr.Dropdown(
|
128 |
+
choices=list(themes.items()),
|
129 |
+
label="Tema",
|
130 |
+
value="casamento"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
131 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
132 |
|
133 |
+
verse_box = gr.Textbox(
|
134 |
+
label="✨ Versículo do Dia",
|
135 |
+
value=get_daily_verse(),
|
136 |
+
interactive=False
|
137 |
+
)
|
|
|
|
|
|
|
|
|
138 |
|
139 |
+
question = gr.Textbox(
|
140 |
+
label="💭 Sua Pergunta",
|
141 |
+
placeholder="Digite sua pergunta aqui...",
|
142 |
+
lines=3
|
143 |
+
)
|
|
|
144 |
|
145 |
+
with gr.Row():
|
146 |
+
submit_btn = gr.Button("🙏 Buscar Orientação", variant="primary")
|
147 |
+
clear_btn = gr.Button("🔄 Limpar")
|
148 |
+
|
149 |
+
with gr.Column():
|
150 |
+
answer_output = gr.Markdown()
|
151 |
+
references = gr.Textbox(
|
152 |
+
label="📚 Referências",
|
153 |
+
interactive=False
|
154 |
+
)
|
155 |
+
|
156 |
+
# Exemplos
|
157 |
+
gr.Examples(
|
158 |
+
examples=[
|
159 |
+
["casamento", "Como resolver conflitos no casamento?"],
|
160 |
+
["casamento", "Como manter um casamento forte?"],
|
161 |
+
["criacao_filhos", "Como educar filhos segundo a Bíblia?"],
|
162 |
+
["criacao_filhos", "Como disciplinar com amor?"],
|
163 |
+
["casamento", "Como orar pelo casamento?"]
|
164 |
+
],
|
165 |
+
inputs=[theme, question],
|
166 |
+
outputs=[answer_output, references],
|
167 |
+
fn=lambda t, q: counselor.get_answer(t, q)
|
168 |
+
)
|
169 |
|
170 |
# Eventos
|
171 |
def clear_outputs():
|
172 |
+
return gr.Textbox.update(value=""), gr.Markdown.update(value=""), gr.Textbox.update(value="")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
173 |
|
|
|
174 |
submit_btn.click(
|
175 |
+
fn=counselor.get_answer,
|
176 |
inputs=[theme, question],
|
177 |
outputs=[answer_output, references]
|
178 |
)
|
179 |
+
|
180 |
clear_btn.click(
|
181 |
fn=clear_outputs,
|
182 |
inputs=[],
|
183 |
outputs=[question, answer_output, references]
|
184 |
)
|
185 |
+
|
186 |
+
# Atualiza versículo diariamente
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
187 |
demo.load(
|
188 |
+
fn=get_daily_verse,
|
189 |
inputs=[],
|
190 |
outputs=[verse_box]
|
191 |
)
|
|
|
194 |
|
195 |
if __name__ == "__main__":
|
196 |
try:
|
197 |
+
logger.info("Iniciando aplicação...")
|
198 |
+
demo = create_interface()
|
199 |
demo.launch(
|
200 |
server_name="0.0.0.0",
|
201 |
share=True,
|