File size: 1,570 Bytes
4a2c63e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
from pathlib import Path
from typing import Optional, Dict, List


class KnowledgeBase:
    """Simple FAQ retrieval system with keyword matching."""
    
    def __init__(self, faq_path: str = "data/faq.json"):
        self.faq_path = Path(faq_path)
        self.faqs = []
        self.load_faq()
    
    def load_faq(self):
        """Load FAQ from JSON file."""
        if self.faq_path.exists():
            with open(self.faq_path, 'r') as f:
                data = json.load(f)
                self.faqs = data.get("faqs", [])
    
    def retrieve_answer(self, user_message: str) -> Optional[Dict]:
        """

        Retrieve relevant FAQ answer using keyword matching.

        

        Args:

            user_message: User's input message

        

        Returns:

            FAQ item with answer, or None if no match found

        """
        user_message_lower = user_message.lower()
        
        # Score FAQs based on keyword matches
        scores = []
        for faq in self.faqs:
            keywords = faq.get("keywords", [])
            matches = sum(1 for kw in keywords if kw.lower() in user_message_lower)
            
            if matches > 0:
                scores.append((faq, matches))
        
        # Return FAQ with highest match score
        if scores:
            top_faq = max(scores, key=lambda x: x[1])[0]
            return top_faq
        
        return None
    
    def get_all_faqs(self) -> List[Dict]:
        """Get all FAQs."""
        return self.faqs