File size: 20,453 Bytes
6e827c2
f69b9a6
 
4263f88
f69b9a6
8f0f662
3f3176a
b9c754c
8445ab0
 
8f0f662
 
 
20a9402
f6cb88d
20a9402
f69b9a6
6e827c2
8445ab0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9288fb
8f0f662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8445ab0
b9288fb
f756686
b9288fb
f756686
 
b9c754c
b4fe7ab
8f0f662
b4fe7ab
 
 
 
 
 
 
 
 
 
 
 
 
 
b9288fb
 
b4fe7ab
 
 
 
8f0f662
 
 
b9288fb
b4fe7ab
8f0f662
 
 
 
 
 
 
b4fe7ab
b9288fb
 
 
8f0f662
b9288fb
b4fe7ab
8f0f662
 
 
 
b4fe7ab
b9288fb
8f0f662
b9288fb
 
b4fe7ab
8f0f662
b4fe7ab
 
 
 
 
 
 
 
 
8f0f662
 
 
b4fe7ab
8f0f662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4fe7ab
b9288fb
8f0f662
 
 
 
b9288fb
 
f5eff85
8f0f662
 
 
 
 
 
 
 
 
 
 
 
 
 
8445ab0
 
 
a15a384
8f0f662
 
 
 
 
 
 
 
 
 
 
b9288fb
8f0f662
b9288fb
 
 
 
 
 
8445ab0
 
b9288fb
35edc8e
a15a384
b9288fb
35edc8e
8445ab0
b9288fb
35edc8e
b4fe7ab
 
 
a15a384
 
8f0f662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9288fb
8f0f662
 
 
 
 
 
 
a15a384
 
b9288fb
8f0f662
b9288fb
 
 
 
 
 
 
 
 
 
8f0f662
b9288fb
 
 
b4fe7ab
8f0f662
b4fe7ab
 
 
8f0f662
 
b4fe7ab
 
b9288fb
8f0f662
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9288fb
 
 
 
f756686
b9288fb
 
f756686
 
 
b9288fb
8445ab0
b4fe7ab
b9288fb
8445ab0
 
 
b9288fb
 
8445ab0
b4fe7ab
8445ab0
 
 
 
b9c754c
b9288fb
b4fe7ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f0f662
b4fe7ab
 
 
 
 
 
 
 
b9288fb
 
 
 
 
 
f756686
3f3176a
6e827c2
 
20a9402
b9288fb
 
32648a9
 
 
35edc8e
 
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import gradio as gr
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
import torch
import logging
import warnings
from typing import List, Tuple, Dict, Optional
import random
from datetime import datetime
from dataclasses import dataclass
from enum import Enum
from difflib import SequenceMatcher
import numpy as np
import re

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
warnings.filterwarnings('ignore')

class ThemeType(Enum):
    MARRIAGE = "casamento"
    FAMILY = "familia"
    SPIRITUAL = "vida_espiritual"
    WORK = "trabalho"
    RELATIONSHIPS = "relacionamentos"
    GENERAL = "geral"

@dataclass
class BiblicalExample:
    question: str
    passage: str
    text: str
    base_response: str
    application: str
    sentiment: str
    keywords: List[str] = None
    theme: str = ""

    def __post_init__(self):
        if self.keywords is None:
            self.keywords = self.extract_keywords()

    def extract_keywords(self) -> List[str]:
        """Extract meaningful keywords from question and response."""
        text = f"{self.question} {self.base_response}"
        words = text.lower().split()
        # Remove common Portuguese stop words
        stop_words = {'a', 'o', 'e', 'de', 'do', 'da', 'em', 'para', 'com', 'um', 'uma'}
        keywords = [word for word in words if len(word) > 3 and word not in stop_words]
        return list(set(keywords))

class TextProcessor:
    @staticmethod
    def normalize_text(text: str) -> str:
        """Normalize text by removing special characters and extra spaces."""
        text = re.sub(r'[^\w\s]', ' ', text)
        text = ' '.join(text.lower().split())
        return text

    @staticmethod
    def extract_main_concepts(text: str) -> List[str]:
        """Extract main concepts from text using basic NLP techniques."""
        # Remove common words and keep meaningful terms
        stop_words = {'a', 'o', 'e', 'de', 'do', 'da', 'em', 'para', 'com', 'um', 'uma', 'que', 'como'}
        words = TextProcessor.normalize_text(text).split()
        concepts = [word for word in words if word not in stop_words and len(word) > 3]
        return list(set(concepts))

class ResponseValidator:
    def __init__(self):
        self.text_processor = TextProcessor()
        self.similarity_threshold = 0.3
        self.keyword_threshold = 0.2
        self.concept_match_threshold = 0.25

    def calculate_text_similarity(self, text1: str, text2: str) -> float:
        """Calculate text similarity using SequenceMatcher."""
        normalized_text1 = self.text_processor.normalize_text(text1)
        normalized_text2 = self.text_processor.normalize_text(text2)
        return SequenceMatcher(None, normalized_text1, normalized_text2).ratio()

    def calculate_keyword_similarity(self, text1: str, text2: str) -> float:
        """Calculate keyword similarity between texts."""
        keywords1 = set(self.text_processor.extract_main_concepts(text1))
        keywords2 = set(self.text_processor.extract_main_concepts(text2))
        if not keywords1 or not keywords2:
            return 0.0
        return len(keywords1.intersection(keywords2)) / len(keywords1.union(keywords2))

    def calculate_concept_similarity(self, question: str, example: BiblicalExample) -> float:
        """Calculate concept similarity between question and example."""
        question_concepts = set(self.text_processor.extract_main_concepts(question))
        example_concepts = set(example.keywords)
        if not question_concepts or not example_concepts:
            return 0.0
        return len(question_concepts.intersection(example_concepts)) / len(question_concepts.union(example_concepts))

    def validate_response(self, question: str, example: BiblicalExample) -> Tuple[bool, Dict[str, float]]:
        """Validate response relevance using multiple metrics."""
        text_similarity = self.calculate_text_similarity(question, example.question)
        keyword_similarity = self.calculate_keyword_similarity(question, example.question)
        concept_similarity = self.calculate_concept_similarity(question, example)

        # Calculate weighted score
        weights = {'text': 0.4, 'keyword': 0.3, 'concept': 0.3}
        total_score = (
            text_similarity * weights['text'] +
            keyword_similarity * weights['keyword'] +
            concept_similarity * weights['concept']
        )

        metrics = {
            'text_similarity': round(text_similarity, 3),
            'keyword_similarity': round(keyword_similarity, 3),
            'concept_similarity': round(concept_similarity, 3),
            'total_score': round(total_score, 3)
        }

        is_valid = (
            text_similarity >= self.similarity_threshold or
            keyword_similarity >= self.keyword_threshold or
            concept_similarity >= self.concept_match_threshold
        )

        return is_valid, metrics

class SapienciaBiblica:
    def __init__(self):
        logger.info("Inicializando SapiênciaBíblica...")
        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 = []
        self.biblical_examples = self.get_default_examples_dict()
        self.validator = ResponseValidator()
        self.setup_model()

    def setup_model(self):
        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 get_default_examples_dict(self) -> Dict[str, List[BiblicalExample]]:
        return {
            "casamento": [
                BiblicalExample(
                    question="Como melhorar a comunicação no casamento?",
                    passage="Efésios 4:29",
                    text="Não saia da vossa boca nenhuma palavra torpe, mas só a que for boa para promover a edificação, para que dê graça aos que a ouvem.",
                    base_response="A comunicação efetiva no casamento requer sabedoria, paciência e amor. A Bíblia nos ensina a usar palavras que edificam e não destroem.",
                    application="Pratique escuta ativa, escolha momentos adequados para conversas importantes, e sempre fale com amor e respeito.",
                    sentiment="supportive",
                    theme="casamento"
                ),
                BiblicalExample(
                    question="Como lidar com conflitos no casamento?",
                    passage="Efésios 4:26-27",
                    text="Irai-vos e não pequeis; não se ponha o sol sobre a vossa ira. Não deis lugar ao diabo.",
                    base_response="Os conflitos são naturais, mas devem ser resolvidos com sabedoria e amor, sem deixar que a raiva tome conta.",
                    application="Resolva os conflitos no mesmo dia, pratique o perdão e busque entender o ponto de vista do cônjuge.",
                    sentiment="instructive",
                    theme="casamento"
                )
            ],
            "familia": [
                BiblicalExample(
                    question="Como educar filhos segundo a Bíblia?",
                    passage="Provérbios 22:6",
                    text="Instrui o menino no caminho em que deve andar, e até quando envelhecer não se desviará dele.",
                    base_response="A educação dos filhos deve ser baseada em princípios bíblicos, com amor, disciplina e exemplo.",
                    application="Estabeleça rotinas de devocional em família, seja exemplo de caráter e aplique disciplina com amor.",
                    sentiment="instructive",
                    theme="familia"
                )
            ],
            # Add more categories and examples as needed
        }

    def find_best_theme(self, question: str) -> str:
        """Find the most relevant theme for the question."""
        question = question.lower()
        theme_keywords = {
            "casamento": ["casamento", "cônjuge", "esposa", "marido", "casal"],
            "familia": ["família", "filhos", "pais", "criação", "lar"],
            "vida_espiritual": ["oração", "jejum", "adoração", "espiritual", "fé"],
            "trabalho": ["trabalho", "emprego", "carreira", "profissão"],
            "relacionamentos": ["amizade", "relacionamento", "conflito", "perdão"],
        }
        
        max_matches = 0
        best_theme = "geral"
        
        for theme, keywords in theme_keywords.items():
            matches = sum(1 for keyword in keywords if keyword in question)
            if matches > max_matches:
                max_matches = matches
                best_theme = theme
        
        return best_theme

    def find_best_example(self, question: str, theme: str) -> Tuple[Optional[BiblicalExample], Dict[str, float]]:
        """Find the most relevant example and return validation metrics."""
        examples = self.biblical_examples.get(theme, self.biblical_examples["geral"])
        best_score = 0
        best_example = None
        best_metrics = {}
        
        for example in examples:
            is_valid, metrics = self.validator.validate_response(question, example)
            
            if is_valid and metrics['total_score'] > best_score:
                best_score = metrics['total_score']
                best_example = example
                best_metrics = metrics
        
        return best_example, best_metrics

    def get_unique_response(self, question: str, theme: str = None) -> Tuple[str, Dict, str]:
        """Get a validated response for the given question."""
        if not question.strip():
            return "Por favor, faça uma pergunta específica.", {}, self.format_history()
            
        if not theme or theme not in self.biblical_examples:
            theme = self.find_best_theme(question)
        
        best_example, validation_metrics = self.find_best_example(question, theme)
        
        if not best_example:
            response = self.generate_fallback_response(question, theme)
            metadata = {
                "theme": theme,
                "status": "no_matching_example",
                "validation_metrics": validation_metrics
            }
            return response, metadata, self.format_history()
        
        sentiment = self.analyze_sentiment(question)
        response = self.format_response(best_example, sentiment)
        metadata = self.create_metadata(best_example, theme, validation_metrics)
        history = self.save_to_history(question, theme, response, metadata)
        
        return response, metadata, history

    def analyze_sentiment(self, text: str) -> str:
        """Analyze the sentiment of the input text."""
        positive_words = {'alegria', 'esperança', 'paz', 'amor', 'gratidão', 'feliz', 'bem'}
        negative_words = {'tristeza', 'medo', 'ansiedade', 'preocupação', 'angústia', 'mal', 'dor'}
        
        text_words = set(text.lower().split())
        pos_count = len(text_words.intersection(positive_words))
        neg_count = len(text_words.intersection(negative_words))
        
        return 'positive' if pos_count > neg_count else 'negative' if neg_count > pos_count else 'neutral'

    def format_response(self, example: BiblicalExample, sentiment: str) -> str:
        """Format the response with appropriate introduction based on sentiment."""
        intro = {
            'positive': "Que bom que você está buscando orientação! ",
            'negative': "Entendo seu momento e estou aqui para ajudar. ",
            'neutral': "Agradeço sua busca por sabedoria. "
        }
        
        return f"""
🌟 Orientação Personalizada:
{intro[sentiment]}{example.base_response}

📖 Passagem Bíblica:
{example.passage}: {example.text}

✨ Aplicação Prática:
{example.application}

🙏 Observação: 
Esta orientação é baseada em princípios bíblicos. Para questões específicas, 
considere consultar sua liderança espiritual local.
"""

    def generate_fallback_response(self, question: str, theme: str) -> str:
        """Generate a thoughtful fallback response when no good match is found."""
        theme_verses = {
            "casamento": ("Efésios 5:25", "Maridos, amai vossas mulheres, como também Cristo amou a igreja..."),
            "familia": ("Salmos 127:3", "Eis que os filhos são herança do Senhor..."),
            "vida_espiritual": ("Filipenses 4:6", "Não andeis ansiosos por coisa alguma..."),
            "trabalho": ("Colossenses 3:23", "E tudo quanto fizerdes, fazei-o de coração..."),
            "relacionamentos": ("João 13:34", "Um novo mandamento vos dou: Que vos ameis uns aos outros..."),
            "geral": ("Provérbios 3:5-6", "Confia no Senhor de todo o teu coração...")
        }
        
        verse = theme_verses.get(theme, theme_verses["geral"])
        
        return f"""
🤔 Compreendo sua busca por orientação sobre {theme}...

Para melhor atendê-lo, considere reformular sua pergunta de forma mais específica, 
mencionando detalhes da situação que você gostaria de abordar.

📖 Enquanto isso, reflita sobre esta passagem:
{verse[0]}: "{verse[1]}"

🙏 Lembre-se: 
"Porque o SENHOR dá a sabedoria, e da sua boca vem o conhecimento e o entendimento." 
- Provérbios 2:6
"""

    def create_metadata(self, example: BiblicalExample, theme: str, validation_metrics: Dict[str, float]) -> Dict:
        """Create comprehensive metadata for the response."""
        return {
            "theme": theme,
            "passage": example.passage,
            "application": example.application,
            "sentiment": example.sentiment,
            "validation_metrics": validation_metrics,
            "keywords_matched": example.keywords,
            "response_quality": "high" if validation_metrics['total_score'] > 0.6 else "medium" if validation_metrics['total_score'] > 0.4 else "low"
        }

    def save_to_history(self, question: str, theme: str, response: str, metadata: Dict) -> str:
        """Save interaction to history and return formatted history."""
        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:
        """Format the session history for display."""
        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:]):  # Show last 5 entries
            history_text += f"🕒 {entry['timestamp']}\n"
            history_text += f"📌 Tema: {entry['theme']}\n"
            history_text += f"❓ Pergunta: {entry['question']}\n"
            if 'validation_metrics' in entry['metadata']:
                history_text += f"📊 Relevância: {entry['metadata']['validation_metrics']['total_score']:.2f}\n"
            history_text += "─" * 40 + "\n"
        return history_text

    def get_verse_of_day(self) -> str:
        """Get a random verse of the day."""
        verses = [
            ("João 3:16", "Porque Deus amou o mundo de tal maneira que deu o seu Filho unigênito, para que todo aquele que nele crê não pereça, mas tenha a vida eterna."),
            ("Salmos 23:1", "O Senhor é meu pastor e nada me faltará."),
            ("Filipenses 4:13", "Posso todas as coisas em Cristo que me fortalece."),
            ("Jeremias 29:11", "Porque eu bem sei os pensamentos que tenho a vosso respeito, diz o Senhor; pensamentos de paz, e não de mal, para vos dar o fim que esperais."),
            ("Provérbios 3:5-6", "Confia no Senhor de todo o teu coração, e não te estribes no teu próprio entendimento. Reconhece-o em todos os teus caminhos, e ele endireitará as tuas veredas.")
        ]
        verse = random.choice(verses)
        return f"📖 Versículo do Dia:\n{verse[0]}\n\n{verse[1]}"

    def get_daily_prayer_focus(self) -> str:
        """Get a random prayer focus for the day."""
        focuses = [
            ("Gratidão e Louvor", "Agradecer a Deus por suas bênçãos e manifestar louvor"),
            ("Família e Relacionamentos", "Orar pela harmonia e proteção familiar"),
            ("Sabedoria e Direção", "Buscar orientação divina para decisões"),
            ("Paz e Serenidade", "Cultivar a paz interior e confiar em Deus"),
            ("Cura e Restauração", "Buscar a cura emocional e espiritual")
        ]
        focus = random.choice(focuses)
        return f"🙏 Foco de Oração:\n{focus[0]}\n{focus[1]}"

    def get_examples_for_interface(self) -> List[List[str]]:
        """Get formatted examples for the Gradio interface."""
        examples = []
        for theme in self.biblical_examples:
            for example in self.biblical_examples[theme]:
                examples.append([theme, example.question])
        return examples

def create_interface():
    counselor = SapienciaBiblica()

    with gr.Blocks(theme=gr.themes.Soft()) as demo:
        gr.Markdown("""
        # 🕊️ SapiênciaBíblica
        ### Orientação Divina para Vida Moderna
        """)

        with gr.Row():
            with gr.Column():
                verse_of_day = gr.Textbox(
                    label="📖 Versículo do Dia",
                    value=counselor.get_verse_of_day(),
                    lines=4,
                    interactive=False
                )
                
            with gr.Column():
                prayer_focus = gr.Textbox(
                    label="🙏 Foco de Oração",
                    value=counselor.get_daily_prayer_focus(),
                    lines=4,
                    interactive=False
                )

        with gr.Row():
            with gr.Column():
                theme = gr.Dropdown(
                    choices=[t.value for t in ThemeType],
                    label="🎯 Tema (Opcional)",
                    value="geral",
                    info="Selecione um tema ou deixe em automático"
                )
                
                question = gr.Textbox(
                    label="❓ Sua Pergunta",
                    placeholder="Digite sua pergunta sobre qualquer tema bíblico...",
                    lines=3
                )
                
                submit_btn = gr.Button("🙏 Buscar Orientação", variant="primary")

            with gr.Column():
                answer_output = gr.Textbox(
                    label="✨ Orientação",
                    lines=12
                )
                
                with gr.Accordion("📚 Detalhes"):
                    metadata_output = gr.JSON(
                        label="📋 Informações Detalhadas"
                    )
                    
                    history_output = gr.Textbox(
                        label="📚 Histórico",
                        lines=10,
                        interactive=False
                    )

        # Examples for the interface
        gr.Examples(
            examples=counselor.get_examples_for_interface(),
            inputs=[theme, question],
            outputs=[answer_output, metadata_output, history_output],
            fn=counselor.get_unique_response,
            label="📝 Exemplos de Perguntas",
            examples_per_page=5
        )

        submit_btn.click(
            fn=counselor.get_unique_response,
            inputs=[question, theme],
            outputs=[answer_output, metadata_output, history_output]
        )

    return demo

if __name__ == "__main__":
    try:
        logger.info("Iniciando SapiênciaBíblica...")
        demo = create_interface()
        demo.launch(
            server_name="0.0.0.0",
            share=True,
            show_error=True,
            server_port=7860
        )
    except Exception as e:
        logger.error(f"Erro ao iniciar aplicação: {str(e)}")
        raise