Spaces:
Sleeping
Sleeping
File size: 7,651 Bytes
6e827c2 f69b9a6 4263f88 f69b9a6 3f3176a f5eff85 b9c754c 20a9402 f6cb88d 20a9402 f69b9a6 6e827c2 b9c754c f5eff85 f756686 b9c754c f756686 b9c754c f5eff85 b9c754c f5eff85 b9c754c f5eff85 b9c754c f756686 b9c754c f756686 f5eff85 f756686 f5eff85 f756686 b9c754c f756686 b9c754c f756686 b9c754c f5eff85 b9c754c f5eff85 f756686 b9c754c 32648a9 b9c754c 32648a9 b9c754c 6ad6360 f756686 3f3176a 6e827c2 20a9402 f756686 32648a9 f5eff85 32648a9 20a9402 |
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 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
import gradio as gr
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
import torch
import logging
import warnings
from typing import List, Tuple, Dict
import random
import hashlib
from datetime import datetime
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
warnings.filterwarnings('ignore')
# Existing BIBLICAL_EXAMPLES dictionary remains the same...
class DiverseBiblicalCounselor:
def __init__(self):
logger.info("Inicializando conselheiro bíblico...")
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.model_name = "pierreguillou/bert-base-cased-squad-v1.1-portuguese"
self.session_history = []
try:
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
self.model = AutoModelForQuestionAnswering.from_pretrained(self.model_name)
self.model.to(self.device)
logger.info(f"Modelo carregado com sucesso no dispositivo: {self.device}")
except Exception as e:
logger.error(f"Erro ao carregar modelo: {str(e)}")
raise
def save_to_history(self, question: str, theme: str, response: str, metadata: Dict):
"""Salva a consulta no histórico com timestamp"""
self.session_history.append({
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"theme": theme,
"question": question,
"response": response,
"metadata": metadata
})
return self.format_history()
def format_history(self) -> str:
"""Formata o histórico de consultas para exibição"""
if not self.session_history:
return "Nenhuma consulta realizada ainda."
history_text = "📚 Histórico de Consultas:\n\n"
for entry in reversed(self.session_history[-5:]): # Shows last 5 consultations
history_text += f"🕒 {entry['timestamp']}\n"
history_text += f"📌 Tema: {entry['theme']}\n"
history_text += f"❓ Pergunta: {entry['question']}\n"
history_text += f"📖 Passagem: {entry['metadata']['passagem']}\n"
history_text += "─" * 50 + "\n"
return history_text
def get_verse_of_the_day(self) -> str:
"""Retorna um versículo diário baseado na data"""
all_verses = []
for theme_examples in BIBLICAL_EXAMPLES.values():
for example in theme_examples:
all_verses.append({
'passagem': example['passagem'],
'texto': example['texto']
})
# Use a data atual como seed para selecionar o versículo
today = datetime.now().strftime("%Y%m%d")
random.seed(today)
verse = random.choice(all_verses)
return f"📖 Versículo do Dia:\n{verse['passagem']}\n\n{verse['texto']}"
def get_unique_response(self, question: str, theme: str) -> Tuple[str, Dict]:
"""Gera uma resposta única baseada na pergunta e tema"""
# Previous implementation remains the same...
# Get response and metadata as before
response, metadata = super().get_unique_response(question, theme) # Assuming this exists
# Save to history
history = self.save_to_history(question, theme, response, metadata)
return response, metadata, history
def create_interface():
counselor = DiverseBiblicalCounselor()
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# 🕊️ Conselheiro Bíblico
### Orientação Bíblica Personalizada
""")
# Verse of the day section
with gr.Row():
verse_of_day = gr.Textbox(
label="Versículo do Dia",
value=counselor.get_verse_of_the_day(),
lines=4,
interactive=False
)
with gr.Tabs():
with gr.TabItem("📝 Consulta"):
with gr.Row():
with gr.Column():
theme = gr.Dropdown(
choices=list(BIBLICAL_EXAMPLES.keys()),
label="Tema",
value="casamento"
)
question = gr.Textbox(
label="Sua Pergunta",
placeholder="Digite sua pergunta...",
lines=3
)
submit_btn = gr.Button("🙏 Buscar Orientação", variant="primary")
with gr.Column():
answer_output = gr.Textbox(
label="Resposta",
lines=10
)
metadata_output = gr.Textbox(
label="Referências",
lines=3
)
with gr.TabItem("📚 Histórico"):
history_output = gr.Textbox(
label="Histórico de Consultas",
value="Nenhuma consulta realizada ainda.",
lines=15,
interactive=False
)
with gr.TabItem("ℹ️ Ajuda"):
gr.Markdown("""
### Como usar o Conselheiro Bíblico:
1. Selecione um tema relacionado à sua dúvida
2. Digite sua pergunta de forma clara e objetiva
3. Clique em "Buscar Orientação"
4. Receba orientação baseada em princípios bíblicos
### Temas Disponíveis:
- Casamento: Conselhos para relacionamento conjugal
- Criação de Filhos: Orientação para pais
- [outros temas conforme disponível no sistema]
### Notas:
- As respostas são baseadas em princípios bíblicos
- Cada consulta é salva no histórico para referência futura
- O versículo do dia é atualizado diariamente
""")
# Examples section
gr.Examples(
examples=[
["casamento", "Como resolver conflitos no casamento?"],
["casamento", "Como manter um casamento forte espiritualmente?"],
["casamento", "Qual o papel do perdão no casamento?"],
["casamento", "Como manter a fidelidade no casamento?"],
["casamento", "Como lidar com diferenças no casamento?"]
],
inputs=[theme, question],
outputs=[answer_output, metadata_output, history_output],
fn=lambda t, q: counselor.get_unique_response(q, t),
label="Exemplos de Perguntas"
)
def update_outputs(theme, question):
response, metadata, history = counselor.get_unique_response(question, theme)
return response, metadata, history
submit_btn.click(
fn=update_outputs,
inputs=[theme, question],
outputs=[answer_output, metadata_output, history_output]
)
return demo
if __name__ == "__main__":
try:
logger.info("Iniciando aplicação...")
demo = create_interface()
demo.launch(
server_name="0.0.0.0",
share=True,
show_error=True
)
except Exception as e:
logger.error(f"Erro ao iniciar aplicação: {str(e)}")
raise |