DHEIVER's picture
Update app.py
b9c754c verified
raw
history blame
7.65 kB
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