Upload folder using huggingface_hub
Browse files- __init__.py +0 -0
- __pycache__/__init__.cpython-312.pyc +0 -0
- __pycache__/retriever.cpython-312.pyc +0 -0
- retriever.py +49 -0
__init__.py
ADDED
|
File without changes
|
__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (147 Bytes). View file
|
|
|
__pycache__/retriever.cpython-312.pyc
ADDED
|
Binary file (2.74 kB). View file
|
|
|
retriever.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import numpy as np
|
| 3 |
+
from sentence_transformers import SentenceTransformer
|
| 4 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 5 |
+
|
| 6 |
+
class KnowledgeRetriever:
|
| 7 |
+
def __init__(self, knowledge_base_path="knowledge_base.json"):
|
| 8 |
+
self.embedder = SentenceTransformer('all-MiniLM-L6-v2')
|
| 9 |
+
|
| 10 |
+
# Load knowledge base
|
| 11 |
+
with open(knowledge_base_path, 'r') as f:
|
| 12 |
+
self.kb = json.load(f)
|
| 13 |
+
|
| 14 |
+
self.content = self.kb['content']
|
| 15 |
+
self.embeddings = np.array(self.kb['embeddings'])
|
| 16 |
+
|
| 17 |
+
def retrieve_relevant_content(self, query, top_k=5, min_similarity=0.3):
|
| 18 |
+
"""Retrieve most relevant content for the query"""
|
| 19 |
+
|
| 20 |
+
# Encode query
|
| 21 |
+
query_embedding = self.embedder.encode([query])
|
| 22 |
+
|
| 23 |
+
# Calculate similarities
|
| 24 |
+
similarities = cosine_similarity(query_embedding, self.embeddings)[0]
|
| 25 |
+
|
| 26 |
+
# Get top results above threshold
|
| 27 |
+
top_indices = np.argsort(similarities)[-top_k:][::-1]
|
| 28 |
+
|
| 29 |
+
relevant_content = []
|
| 30 |
+
for idx in top_indices:
|
| 31 |
+
if similarities[idx] >= min_similarity:
|
| 32 |
+
content_item = self.content[idx].copy()
|
| 33 |
+
content_item['similarity_score'] = float(similarities[idx])
|
| 34 |
+
relevant_content.append(content_item)
|
| 35 |
+
|
| 36 |
+
return relevant_content
|
| 37 |
+
|
| 38 |
+
def format_context_for_llm(self, relevant_content):
|
| 39 |
+
"""Format retrieved content for LLM context"""
|
| 40 |
+
if not relevant_content:
|
| 41 |
+
return "No relevant information found in WebAIM resources."
|
| 42 |
+
|
| 43 |
+
context = "Relevant information from WebAIM resources:\n\n"
|
| 44 |
+
|
| 45 |
+
for i, item in enumerate(relevant_content, 1):
|
| 46 |
+
context += f"[Source {i}] From {item['source_file']} (Page {item['page_number']}):\n"
|
| 47 |
+
context += f"{item['text']}\n\n"
|
| 48 |
+
|
| 49 |
+
return context
|