Spaces:
Sleeping
Sleeping
File size: 10,863 Bytes
41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 a5778f2 41bd0b8 | 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 | """
Knowledge Base Manager for Too Many Cables
Handles loading, organizing, and managing company knowledge documents
"""
import os
import json
import hashlib
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional, Tuple
class KnowledgeBaseManager:
def __init__(self, knowledge_base_path: str = "knowledge_base"):
"""Initialize the knowledge base manager"""
self.kb_path = Path(knowledge_base_path)
self.documents = {}
self.document_index = {}
self.metadata_file = self.kb_path / "metadata.json"
# Ensure knowledge base directory exists
self.kb_path.mkdir(exist_ok=True)
# Load existing metadata if it exists
self.load_metadata()
def load_metadata(self):
"""Load document metadata from file"""
if self.metadata_file.exists():
try:
with open(self.metadata_file, 'r', encoding='utf-8') as f:
metadata = json.load(f)
self.document_index = metadata.get('documents', {})
except Exception as e:
print(f"Error loading metadata: {e}")
self.document_index = {}
def save_metadata(self):
"""Save document metadata to file"""
metadata = {
'last_updated': datetime.now().isoformat(),
'total_documents': len(self.document_index),
'documents': self.document_index
}
try:
with open(self.metadata_file, 'w', encoding='utf-8') as f:
json.dump(metadata, f, indent=2)
except Exception as e:
print(f"Error saving metadata: {e}")
def scan_documents(self) -> Dict[str, Dict]:
"""Scan knowledge base directory and catalog all documents"""
documents = {}
# Define document categories and their directories
categories = {
'faqs': 'Frequently Asked Questions',
'policies': 'Company Policies',
'product_manuals': 'Product Manuals',
'troubleshooting': 'Troubleshooting Guides',
'development': 'Internal Development Documentation'
}
for category, description in categories.items():
category_path = self.kb_path / category
if category_path.exists():
documents[category] = {
'description': description,
'documents': []
}
# Scan for markdown files in category
for file_path in category_path.glob('*.md'):
doc_info = self.analyze_document(file_path, category)
if doc_info:
documents[category]['documents'].append(doc_info)
self.documents = documents
return documents
def analyze_document(self, file_path: Path, category: str) -> Optional[Dict]:
"""Analyze a document and extract metadata"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Calculate file hash for change detection
file_hash = hashlib.md5(content.encode()).hexdigest()
# Extract title (first # heading)
title = "Unknown Document"
for line in content.split('\n'):
if line.strip().startswith('# '):
title = line.strip()[2:].strip()
break
# Get file stats
stats = file_path.stat()
doc_info = {
'filename': file_path.name,
'title': title,
'category': category,
'path': str(file_path.relative_to(self.kb_path)),
'size': stats.st_size,
'modified': datetime.fromtimestamp(stats.st_mtime).isoformat(),
'hash': file_hash,
'word_count': len(content.split()),
'char_count': len(content)
}
return doc_info
except Exception as e:
print(f"Error analyzing document {file_path}: {e}")
return None
def load_document_content(self, document_path: str) -> Optional[str]:
"""Load the full content of a specific document"""
try:
full_path = self.kb_path / document_path
with open(full_path, 'r', encoding='utf-8') as f:
return f.read()
except Exception as e:
print(f"Error loading document {document_path}: {e}")
return None
def search_documents(self, query: str, category: Optional[str] = None) -> List[Dict]:
"""Search documents for relevant content"""
results = []
query_lower = query.lower()
for cat_name, cat_info in self.documents.items():
# Skip if category filter specified and doesn't match
if category and cat_name != category:
continue
for doc in cat_info['documents']:
# Load document content for search
content = self.load_document_content(doc['path'])
if not content:
continue
content_lower = content.lower()
# Simple text search - could be enhanced with fuzzy matching
if query_lower in content_lower or query_lower in doc['title'].lower():
# Calculate relevance score (simple word count for now)
relevance = content_lower.count(query_lower)
result = doc.copy()
result['relevance_score'] = relevance
result['category_description'] = cat_info['description']
# Extract context around matches
result['context_snippets'] = self.extract_context(content, query, max_snippets=3)
results.append(result)
# Sort by relevance score
results.sort(key=lambda x: x['relevance_score'], reverse=True)
return results
def extract_context(self, content: str, query: str, max_snippets: int = 3, context_length: int = 200) -> List[str]:
"""Extract context snippets around query matches"""
snippets = []
content_lower = content.lower()
query_lower = query.lower()
start = 0
snippet_count = 0
while snippet_count < max_snippets:
# Find next occurrence of query
pos = content_lower.find(query_lower, start)
if pos == -1:
break
# Extract context around the match
context_start = max(0, pos - context_length // 2)
context_end = min(len(content), pos + len(query) + context_length // 2)
snippet = content[context_start:context_end].strip()
# Add ellipsis if not at beginning/end
if context_start > 0:
snippet = "..." + snippet
if context_end < len(content):
snippet = snippet + "..."
snippets.append(snippet)
snippet_count += 1
start = pos + len(query)
return snippets
def get_document_by_category(self, category: str) -> List[Dict]:
"""Get all documents in a specific category"""
if category in self.documents:
return self.documents[category]['documents']
return []
def get_document_categories(self) -> Dict[str, str]:
"""Get available document categories"""
return {cat: info['description'] for cat, info in self.documents.items()}
def get_stats(self) -> Dict:
"""Get knowledge base statistics"""
total_docs = sum(len(cat['documents']) for cat in self.documents.values())
total_words = sum(doc['word_count'] for cat in self.documents.values() for doc in cat['documents'])
total_size = sum(doc['size'] for cat in self.documents.values() for doc in cat['documents'])
return {
'total_documents': total_docs,
'total_categories': len(self.documents),
'total_words': total_words,
'total_size_bytes': total_size,
'categories': {
cat: len(info['documents'])
for cat, info in self.documents.items()
}
}
def update_index(self):
"""Scan documents and update the index"""
print("Scanning knowledge base documents...")
self.scan_documents()
# Update metadata with document index
for category, cat_info in self.documents.items():
for doc in cat_info['documents']:
doc_id = f"{category}/{doc['filename']}"
self.document_index[doc_id] = doc
self.save_metadata()
print(f"Updated index with {len(self.document_index)} documents")
def get_relevant_documents(self, query: str, max_results: int = 5) -> List[Tuple[str, str, float]]:
"""Get documents most relevant to a query for RAG implementation"""
results = self.search_documents(query)
relevant_docs = []
for result in results[:max_results]:
content = self.load_document_content(result['path'])
if content:
relevant_docs.append((
result['title'],
content,
result['relevance_score']
))
return relevant_docs
def main():
"""Test the knowledge base manager"""
kb = KnowledgeBaseManager()
# Update the index
kb.update_index()
# Show statistics
stats = kb.get_stats()
print("\nKnowledge Base Statistics:")
print(f"Total Documents: {stats['total_documents']}")
print(f"Total Categories: {stats['total_categories']}")
print(f"Total Words: {stats['total_words']:,}")
print(f"Total Size: {stats['total_size_bytes']:,} bytes")
print("\nCategories:")
for category, count in stats['categories'].items():
print(f" {category}: {count} documents")
# Test search functionality
print("\nTesting search for 'USB-C charging':")
results = kb.search_documents("USB-C charging")
for result in results[:3]:
print(f" - {result['title']} (relevance: {result['relevance_score']})")
if result['context_snippets']:
print(f" Context: {result['context_snippets'][0][:100]}...")
if __name__ == "__main__":
main()
|