File size: 8,584 Bytes
20d720d |
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 |
"""
Enhanced setup script with more comprehensive knowledge base
"""
import os
import sys
from pathlib import Path
import numpy as np
import faiss
import pickle
from sentence_transformers import SentenceTransformer
from typing import List, Dict
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# Extended wisdom database with more texts
WISDOM_DATABASE = [
# Bhagavad Gita
{
"text": "The mind is restless and difficult to restrain, but it is subdued by practice.",
"source": "Bhagavad Gita",
"chapter": "6.35",
"tags": ["mind", "practice", "discipline"]
},
{
"text": "Set thy heart upon thy work, but never on its reward.",
"source": "Bhagavad Gita",
"chapter": "2.47",
"tags": ["work", "detachment", "karma"]
},
{
"text": "The soul is neither born, and nor does it die.",
"source": "Bhagavad Gita",
"chapter": "2.20",
"tags": ["soul", "eternal", "death"]
},
# Autobiography of a Yogi
{
"text": "The season of failure is the best time for sowing the seeds of success.",
"source": "Autobiography of a Yogi",
"tags": ["failure", "success", "growth"]
},
{
"text": "Live quietly in the moment and see the beauty of all before you.",
"source": "Autobiography of a Yogi",
"tags": ["present", "beauty", "mindfulness"]
},
# The Power of Now
{
"text": "Realize deeply that the present moment is all you have.",
"source": "The Power of Now",
"tags": ["present", "awareness", "now"]
},
{
"text": "The primary cause of unhappiness is never the situation but your thoughts about it.",
"source": "The Power of Now",
"tags": ["unhappiness", "thoughts", "perception"]
},
{
"text": "Life will give you whatever experience is most helpful for the evolution of your consciousness.",
"source": "The Power of Now",
"tags": ["life", "experience", "consciousness"]
},
# Man's Search for Meaning
{
"text": "When we are no longer able to change a situation, we are challenged to change ourselves.",
"source": "Man's Search for Meaning",
"tags": ["change", "adaptation", "growth"]
},
{
"text": "Those who have a 'why' to live, can bear with almost any 'how'.",
"source": "Man's Search for Meaning",
"tags": ["purpose", "meaning", "resilience"]
},
# Atomic Habits
{
"text": "You do not rise to the level of your goals. You fall to the level of your systems.",
"source": "Atomic Habits",
"tags": ["goals", "systems", "habits"]
},
{
"text": "Every action you take is a vote for the type of person you wish to become.",
"source": "Atomic Habits",
"tags": ["identity", "actions", "becoming"]
},
{
"text": "Habits are the compound interest of self-improvement.",
"source": "Atomic Habits",
"tags": ["habits", "improvement", "compound"]
},
# Meditations - Marcus Aurelius
{
"text": "You have power over your mind - not outside events. Realize this, and you will find strength.",
"source": "Meditations",
"tags": ["control", "mind", "strength"]
},
{
"text": "The best revenge is not to be like your enemy.",
"source": "Meditations",
"tags": ["revenge", "character", "virtue"]
},
{
"text": "What we cannot bear removes us from life; what remains can be borne.",
"source": "Meditations",
"tags": ["endurance", "life", "strength"]
},
# Tao Te Ching
{
"text": "When I let go of what I am, I become what I might be.",
"source": "Tao Te Ching",
"tags": ["letting go", "becoming", "potential"]
},
{
"text": "The journey of a thousand miles begins with a single step.",
"source": "Tao Te Ching",
"tags": ["journey", "beginning", "action"]
},
{
"text": "Knowing others is intelligence; knowing yourself is true wisdom.",
"source": "Tao Te Ching",
"tags": ["self-knowledge", "wisdom", "intelligence"]
},
# 7 Habits of Highly Effective People
{
"text": "Between stimulus and response there is a space. In that space is our power to choose our response.",
"source": "7 Habits of Highly Effective People",
"tags": ["choice", "response", "freedom"]
},
{
"text": "Begin with the end in mind.",
"source": "7 Habits of Highly Effective People",
"tags": ["vision", "planning", "purpose"]
},
# Mindset
{
"text": "Becoming is better than being.",
"source": "Mindset",
"tags": ["growth", "becoming", "fixed mindset"]
},
{
"text": "The view you adopt for yourself profoundly affects the way you lead your life.",
"source": "Mindset",
"tags": ["perspective", "self-view", "life"]
},
# Additional Universal Wisdom
{
"text": "The wound is the place where the Light enters you.",
"source": "Rumi",
"tags": ["pain", "growth", "transformation"]
},
{
"text": "Yesterday I was clever, so I wanted to change the world. Today I am wise, so I am changing myself.",
"source": "Rumi",
"tags": ["change", "wisdom", "self"]
},
{
"text": "Do not dwell in the past, do not dream of the future, concentrate the mind on the present moment.",
"source": "Buddha",
"tags": ["present", "past", "future"]
}
]
def setup_comprehensive_knowledge_base():
"""Setup knowledge base with all wisdom texts"""
print("Setting up comprehensive knowledge base...")
# Create directories
data_dir = Path("data")
faiss_dir = data_dir / "faiss_index"
books_dir = data_dir / "books"
for dir_path in [data_dir, faiss_dir, books_dir]:
dir_path.mkdir(exist_ok=True)
# Initialize embedder
print("Loading sentence transformer model...")
embedder = SentenceTransformer('all-MiniLM-L6-v2')
# Process wisdom texts
texts = []
metadata = []
for item in WISDOM_DATABASE:
texts.append(item["text"])
metadata.append({
"source": item["source"],
"chapter": item.get("chapter", ""),
"tags": item.get("tags", [])
})
# Create embeddings
print(f"Creating embeddings for {len(texts)} wisdom passages...")
embeddings = embedder.encode(texts, show_progress_bar=True)
# Create FAISS index with cosine similarity
dimension = embeddings.shape[1]
# Normalize embeddings for cosine similarity
faiss.normalize_L2(embeddings)
# Use Inner Product (equivalent to cosine similarity after normalization)
index = faiss.IndexFlatIP(dimension)
index.add(embeddings.astype('float32'))
# Save everything
print("Saving knowledge base...")
faiss.write_index(index, str(faiss_dir / "index.faiss"))
with open(faiss_dir / "passages.pkl", 'wb') as f:
pickle.dump(texts, f)
with open(faiss_dir / "metadata.pkl", 'wb') as f:
pickle.dump(metadata, f)
print(f"β
Knowledge base setup complete!")
print(f" - Total passages: {len(texts)}")
print(f" - Embedding dimension: {dimension}")
print(f" - Index type: Cosine similarity (normalized L2)")
# Create placeholder book files
print("\nCreating placeholder book files...")
book_files = [
"bhagavad_gita.txt",
"autobiography_of_a_yogi.txt",
"the_power_of_now.txt",
"mans_search_for_meaning.txt",
"atomic_habits.txt",
"meditations.txt",
"tao_te_ching.txt",
"dhyana_vahini.txt",
"7_habits.txt",
"mindset.txt",
"prema_vahini.txt",
"prasnothara_vahini.txt"
]
for book_file in book_files:
filepath = books_dir / book_file
if not filepath.exists():
with open(filepath, 'w', encoding='utf-8') as f:
f.write(f"Placeholder for {book_file}\nAdd full text here.")
print("β
Setup complete! You can now run the main application.")
print("\nTo add full books:")
print("1. Replace placeholder files in data/books/ with full text")
print("2. Re-run this script to update the knowledge base")
if __name__ == "__main__":
setup_comprehensive_knowledge_base() |