Spaces:
Sleeping
Sleeping
Commit
Β·
2d828c9
1
Parent(s):
5f8d57d
second commit
Browse files- answers/answer_what_is_the_nature_of_consciou.json +31 -0
- create_vector_db.py +6 -1
- osho_qa_service.py +142 -0
- query_vector_db.py +38 -35
- requirements.txt +1 -0
- streamlit_app.py +108 -0
answers/answer_what_is_the_nature_of_consciou.json
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"question": "What is the nature of consciousness?",
|
3 |
+
"answer_passages": [
|
4 |
+
{
|
5 |
+
"passage_number": 1,
|
6 |
+
"book": "Come Follow To You - Vol 2 - Osho.pdf",
|
7 |
+
"text": "consciousness\tis\tjust\ta\twave\ton\tthe\tocean.\tThe\tunconscious\tis\tvast.\"\tThen\tthe\nego\tdisappears.\tEgo\tis\tthe\tpart,\tthinking\titself\tto\tbe\tthe\twhole.\tNon-ego\tis\tthe\npart,\tbecoming\taware\tof\tthe\twhole.\tThen\tthe\tego\tdisappears.\nHow\tto\tdefine\tthe\tnature\tof\tconsciousness?\tIt\thas\tnever\tbeen\tdefined,\tit\tnever\nwill\tbe\tdefined.\tWho\twill\tdefine\tit?\tTo\tdefine\tit\tyou\thave\tto\tbe\taway\tfrom\tit.\tTo\ndefine\tanything\tyou\thave\tto\tstand\tout\tof\tit,\tyou\tneed\ta\tdistance.\tPerspective\twill\nnot\tbe\tpossible\tif\tthe\tdistance\tis\tnot\tthere.\nYou\tare\tconsciousness,\tyou\tARE\tunconsciousness.\tThere\tis\tnobody\twho\tcan\nstand\toutside\tand\tdefine\tit.\tYou\tcan\tknow\tit,\tbut\tyou\tcannot\tdefine\tit.\tThat's\twhy\nall\treligion\tis\tmysterious,\tmystical,\tvague,\tcloudy\t--\tbecause\tno\tterm\twhich\tis\nvery\tbasic\tto\treligion\tcan\tbe\tdefined.\nThe\tsubject\tcannot\tbe\tmade\tan\tobject.\tI\tcannot\tput\tmyself\tin\tfront\tof\tme,\tso\tI\ncannot\tdefine.\tNeither\thas\tBuddha\tdefined,\tnor\tJesus.\tDefinition\tas\tsuch\tis\ndebarred\tby\tthe\tvery\tnature\tof\tthe\tphenomenon."
|
8 |
+
},
|
9 |
+
{
|
10 |
+
"passage_number": 2,
|
11 |
+
"book": "Come Follow To You - Vol 2 - Osho.pdf",
|
12 |
+
"text": "singing;\tcarry\tthe\tcross\tbut\tcarry\tit\twith\ta\tdeep\tcelebration\twithin.\tThen\tyou\tlive\nboth:\tyou\tlive\tlife,\tyou\tlive\tdeath.\tAnd\tyou\tlive\tboth\tof\tthem\tdeeply\tand\nintensely.\tWhen\tyou\tcan\tlive\tboth\tintensely,\tthey\tbecome\tone.\tThen\tyou\tknow\nthat\tlife\tand\tdeath\tare\ttwo\taspects\tof\tthe\tsame\tthing,\tof\tthe\tsame\tenergy.\tLife\tis\nexpression,\tmanifestation.\tDeath\tis\ta\treturning.\nQuestion\t5\nWOULD\tYOU\tDEFINE\tAND\tDISCUSS\tTHE\tNATURE\tOF\nCONSCIOUSNESS?\nHOW\tDOES\tCONSCIOUSNESS\tRELATE\tTO\tEGO?\tIS\tCONSCIOUSNESS\nTHE\nCREATIVE\tPRINCIPLE?\t(THAT\tIS,\tCOULD\tYOU\tSAY\tEQUALLY,\t\"IN\tTHE\nBEGINNING\tWAS\tCONSCIOUSNESS\"\tINSTEAD\tOF\t\"IN\tTHE\tBEGINNING\nWAS\tTHE\tWORD\tOR\tTHE\tLOGOS\"?)\tHOW\tDOES\tCONSCIOUSNESS\nRELATE\nTO\tGOD?\nIn\tthe\tBEGINNING\tWAS\tTHE\tWORD,\tor\tthe\tlogos.\tThe\tsame\tcannot\tbe\tsaid\nabout\tconsciousness,\tbecause\tin\tthe\tbeginning\tunconsciousness\twas\talso\tthere.\nConsciousness\tis\tjust\ta\tpart\tof\tyour\treality,\tthe\treality\tof\tthe\twithin.\nUnconsciousness\tis\talso\tthere.\tSo\tjust\tconsciousness\twas\tnot\tthere\tin\tthe"
|
13 |
+
},
|
14 |
+
{
|
15 |
+
"passage_number": 3,
|
16 |
+
"book": "A Cup of Tea.pdf",
|
17 |
+
"text": "washes them out constantly with every movement,\nand when the whole body is alive\nonly then you begin to feel the cosmic\nconsciousness all around you.\nHow can a frozen consciousness,\nand that too surrounded by a dead body,\nA Cup of Tea 219 Osho\nCHAPTER 1.\nfeel the cosmic?\n228\nNow man knows more about man than ever\nand yet no problem is solved.\nIt seems that something is basically wrong\nwith our so-called knowledge itself.\nThis whole knowledge is derived from analysis\nand analysis is incapable of penetrating\ninto the depths of consciousness.\nThe analytical method is all right with matter or with things\nbecause there is no inside to them,\nbut consciousness is insideness,\nand to use the analytical method with consciousness\nis to treat it as an object\nwhile it is not an object at all.\nAnd it cannot be made an object;\nits very nature is subjectivity,\nits being is subjectivity,\nso it must not be approached from outside\nbecause then whatsoever is known about it is not about it."
|
18 |
+
},
|
19 |
+
{
|
20 |
+
"passage_number": 4,
|
21 |
+
"book": "Blessed Are the Ignorant.pdf",
|
22 |
+
"text": "the conscious is just the tip of the iceberg.\nNow a second discovery is coming closer every day. It is not good to call it a discovery β it\nis a rediscovery, because yoga has known it always. Just as below the conscious there is the\n137\nCHAPTER 22. THERE IS NO NEED TO SEEK HAPPINESS β JUST START LIVING IT\nunconscious, above the conscious there is the superconscious. Just as the unconscious is the dark\nnight, the superconscious is pure light. And all the experiences of the mystics who talk about god\nas pure light, are nothing but the experiences of the superconscious.\nY ou are just in the middle β everybody is just in the middle. The conscious is the link, the bridge,\nbetween the unconscious and the superconscious.\nThe unconscious is the whole of nature, and the superconscious is god. In between the two is\nthe man β just a wavering, a continuous wavering to be this or to be that, to be or not to be... a"
|
23 |
+
},
|
24 |
+
{
|
25 |
+
"passage_number": 5,
|
26 |
+
"book": "Come Follow To You - Vol 2 - Osho.pdf",
|
27 |
+
"text": "is\tjust\ton\tthe\tsurface;\tdeeply\thidden\tare\tlayers\tand\tlayers\tof\tunconsciousness.\nOne\thas\tto\ttranscend\tboth\tto\tknow\tthat\twhich\twas\tin\tthe\tbeginning\t--\twhich\tis\nGod.\n\"Would\tyou\tdefine\tand\tdiscuss\tthe\tnature\tof\tconsciousness?\tHow\tdoes\nconsciousness\trelate\tto\tego?\t\"\tOne\tpart\tof\tyou\tis\tconscious,\tone-tenth.\tNine-\ntenths\tof\tyou\tis\tunconscious.\tIf\tthe\tconscious\tpart\tthinks\titself\tto\tbe\tthe\twhole,\tit\nbecomes\tthe\tego.\tThen\tit\tforgets\tabout\tthe\tunconscious;\tthen\tthe\tpart\timagines\nitself\tto\tbe\tthe\twhole.\tThen\tit\tis\tthe\tego.\nIf\tthe\tconscious\tbecomes\taware\tof\tthe\tunconscious\talso....\tThat\tis\tthe\twhole\neffort\tof\treligion,\tthat\tis\tthe\twhole\teffort\tof\tmeditation.\tIf\tthe\tconscious\tturns\nback,\tlooks\tback,\tand\tbecomes\taware\tof\tthe\tunconscious\talso\t--\tthe\tdark\tnight\nwithin\t--\nthen\tthe\tconscious\tknows\tthat\t\"I\tam\tconscious,\tI\tam\tunconscious\talso.\tMy\nconsciousness\tis\tjust\ta\twave\ton\tthe\tocean.\tThe\tunconscious\tis\tvast.\"\tThen\tthe\nego\tdisappears.\tEgo\tis\tthe\tpart,\tthinking\titself\tto\tbe\tthe\twhole.\tNon-ego\tis\tthe"
|
28 |
+
}
|
29 |
+
],
|
30 |
+
"total_passages": 5
|
31 |
+
}
|
create_vector_db.py
CHANGED
@@ -5,6 +5,7 @@ from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
5 |
import chromadb
|
6 |
from chromadb.utils import embedding_functions
|
7 |
from tqdm import tqdm
|
|
|
8 |
|
9 |
class PDFVectorizer:
|
10 |
def __init__(self, pdf_dir: str, db_dir: str):
|
@@ -17,8 +18,12 @@ class PDFVectorizer:
|
|
17 |
)
|
18 |
# Initialize ChromaDB with sentence-transformers embeddings
|
19 |
self.client = chromadb.PersistentClient(path=db_dir)
|
|
|
|
|
|
|
20 |
self.embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(
|
21 |
-
model_name="all-MiniLM-L6-v2"
|
|
|
22 |
)
|
23 |
self.collection = self.client.create_collection(
|
24 |
name="osho_books",
|
|
|
5 |
import chromadb
|
6 |
from chromadb.utils import embedding_functions
|
7 |
from tqdm import tqdm
|
8 |
+
import torch
|
9 |
|
10 |
class PDFVectorizer:
|
11 |
def __init__(self, pdf_dir: str, db_dir: str):
|
|
|
18 |
)
|
19 |
# Initialize ChromaDB with sentence-transformers embeddings
|
20 |
self.client = chromadb.PersistentClient(path=db_dir)
|
21 |
+
# Check if GPU is available
|
22 |
+
self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
23 |
+
print(f"Using device: {self.device}")
|
24 |
self.embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(
|
25 |
+
model_name="all-MiniLM-L6-v2",
|
26 |
+
device=self.device
|
27 |
)
|
28 |
self.collection = self.client.create_collection(
|
29 |
name="osho_books",
|
osho_qa_service.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Suppress warnings - must be before any imports
|
2 |
+
import os
|
3 |
+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
4 |
+
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
|
5 |
+
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
6 |
+
|
7 |
+
import warnings
|
8 |
+
import logging
|
9 |
+
# Suppress all warnings
|
10 |
+
warnings.filterwarnings('ignore')
|
11 |
+
# Specific suppressions
|
12 |
+
warnings.filterwarnings('ignore', category=UserWarning)
|
13 |
+
warnings.filterwarnings('ignore', category=DeprecationWarning)
|
14 |
+
warnings.filterwarnings('ignore', category=FutureWarning)
|
15 |
+
warnings.filterwarnings('ignore', message='.*benefit from vacuuming.*')
|
16 |
+
warnings.filterwarnings('ignore', message='.*sparse_softmax_cross_entropy.*')
|
17 |
+
|
18 |
+
# Suppress all logging
|
19 |
+
logging.getLogger().setLevel(logging.ERROR)
|
20 |
+
# Suppress TensorFlow logging
|
21 |
+
logging.getLogger('tensorflow').setLevel(logging.ERROR)
|
22 |
+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
23 |
+
|
24 |
+
import json
|
25 |
+
from typing import Dict, List
|
26 |
+
import chromadb
|
27 |
+
from chromadb.utils import embedding_functions
|
28 |
+
|
29 |
+
def clean_text(text: str) -> str:
|
30 |
+
"""Clean the text by removing extra spaces and formatting."""
|
31 |
+
# Remove multiple spaces
|
32 |
+
text = ' '.join(text.split())
|
33 |
+
# Remove unnecessary line breaks
|
34 |
+
text = text.replace('\n', ' ')
|
35 |
+
|
36 |
+
# Remove text before first complete sentence
|
37 |
+
if '.' in text:
|
38 |
+
# Split by period and remove any incomplete sentence at start
|
39 |
+
sentences = text.split('.')
|
40 |
+
# Remove first part if it seems like a partial sentence
|
41 |
+
if len(sentences) > 1: # Only if there are multiple sentences
|
42 |
+
sentences = sentences[1:] # Remove first part
|
43 |
+
text = '.'.join(sentences)
|
44 |
+
text = text.strip() # Remove leading/trailing whitespace
|
45 |
+
if text: # Add period back if text is not empty
|
46 |
+
text += '.'
|
47 |
+
|
48 |
+
return text
|
49 |
+
|
50 |
+
def get_answer_from_osho(question: str, n_results: int = 5) -> Dict:
|
51 |
+
"""
|
52 |
+
Get answer from Osho's books based on the question.
|
53 |
+
|
54 |
+
Args:
|
55 |
+
question (str): The question to ask
|
56 |
+
n_results (int): Number of relevant passages to return
|
57 |
+
|
58 |
+
Returns:
|
59 |
+
Dict: A dictionary containing the question and formatted answer with sources
|
60 |
+
"""
|
61 |
+
# Initialize ChromaDB client
|
62 |
+
db_dir = os.path.join(os.getcwd(), "vector_db")
|
63 |
+
client = chromadb.PersistentClient(path=db_dir)
|
64 |
+
|
65 |
+
# Initialize embedding function
|
66 |
+
embedding_function = embedding_functions.SentenceTransformerEmbeddingFunction(
|
67 |
+
model_name="all-MiniLM-L6-v2"
|
68 |
+
)
|
69 |
+
|
70 |
+
# Get the collection
|
71 |
+
collection = client.get_collection(
|
72 |
+
name="osho_books",
|
73 |
+
embedding_function=embedding_function
|
74 |
+
)
|
75 |
+
|
76 |
+
# Query the collection
|
77 |
+
results = collection.query(
|
78 |
+
query_texts=[question],
|
79 |
+
n_results=n_results
|
80 |
+
)
|
81 |
+
|
82 |
+
# Format the answer
|
83 |
+
answer_parts = []
|
84 |
+
for i, (doc, metadata) in enumerate(zip(results['documents'][0], results['metadatas'][0])):
|
85 |
+
answer_part = {
|
86 |
+
"passage_number": i + 1,
|
87 |
+
"book": metadata['book'],
|
88 |
+
"text": clean_text(doc.strip())
|
89 |
+
}
|
90 |
+
answer_parts.append(answer_part)
|
91 |
+
|
92 |
+
# Create the response
|
93 |
+
response = {
|
94 |
+
"question": question,
|
95 |
+
"answer_passages": answer_parts,
|
96 |
+
"total_passages": len(answer_parts)
|
97 |
+
}
|
98 |
+
|
99 |
+
return response
|
100 |
+
|
101 |
+
def save_qa_to_file(qa_response: Dict, output_file: str = None):
|
102 |
+
"""
|
103 |
+
Save the Q&A response to a JSON file.
|
104 |
+
|
105 |
+
Args:
|
106 |
+
qa_response (Dict): The Q&A response to save
|
107 |
+
output_file (str): Optional output file path. If None, generates a filename
|
108 |
+
"""
|
109 |
+
if output_file is None:
|
110 |
+
# Create answers directory if it doesn't exist
|
111 |
+
answers_dir = os.path.join(os.getcwd(), "answers")
|
112 |
+
os.makedirs(answers_dir, exist_ok=True)
|
113 |
+
|
114 |
+
# Generate filename from question
|
115 |
+
filename = f"answer_{qa_response['question'][:30].lower().replace(' ', '_')}.json"
|
116 |
+
output_file = os.path.join(answers_dir, filename)
|
117 |
+
|
118 |
+
# Save to file
|
119 |
+
with open(output_file, 'w', encoding='utf-8') as f:
|
120 |
+
json.dump(qa_response, f, ensure_ascii=False, indent=2)
|
121 |
+
|
122 |
+
return output_file
|
123 |
+
|
124 |
+
if __name__ == "__main__":
|
125 |
+
# Example usage
|
126 |
+
question = "What is the nature of consciousness?"
|
127 |
+
|
128 |
+
# Get answer
|
129 |
+
response = get_answer_from_osho(question)
|
130 |
+
|
131 |
+
# Save to file
|
132 |
+
output_file = save_qa_to_file(response)
|
133 |
+
|
134 |
+
# Print the response
|
135 |
+
print(f"\nQuestion: {response['question']}\n")
|
136 |
+
for passage in response['answer_passages']:
|
137 |
+
print(f"\nPassage {passage['passage_number']}:")
|
138 |
+
print(f"Book: {passage['book']}")
|
139 |
+
print(f"Text: {passage['text'][:200]}...")
|
140 |
+
print("-" * 80)
|
141 |
+
|
142 |
+
print(f"\nResponse saved to: {output_file}")
|
query_vector_db.py
CHANGED
@@ -1,41 +1,44 @@
|
|
|
|
1 |
import os
|
2 |
-
|
3 |
-
|
|
|
4 |
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
-
#
|
12 |
-
|
13 |
-
model_name="all-MiniLM-L6-v2"
|
14 |
-
)
|
15 |
|
16 |
-
#
|
17 |
-
|
18 |
-
name="osho_books",
|
19 |
-
embedding_function=embedding_function
|
20 |
-
)
|
21 |
|
22 |
-
#
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
)
|
27 |
|
28 |
-
#
|
29 |
-
|
30 |
-
|
31 |
-
print(
|
32 |
-
print(f"Book: {metadata['book']}")
|
33 |
-
print(f"Passage: {doc[:200]}...") # Show first 200 characters
|
34 |
-
print("-" * 80)
|
35 |
-
|
36 |
-
if __name__ == "__main__":
|
37 |
-
while True:
|
38 |
-
query = input("\nEnter your query (or 'quit' to exit): ")
|
39 |
-
if query.lower() == 'quit':
|
40 |
-
break
|
41 |
-
query_vector_db(query)
|
|
|
1 |
+
# Suppress warnings - must be before any imports
|
2 |
import os
|
3 |
+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
4 |
+
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
|
5 |
+
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
6 |
|
7 |
+
import warnings
|
8 |
+
import logging
|
9 |
+
# Suppress all warnings
|
10 |
+
warnings.filterwarnings('ignore')
|
11 |
+
# Specific suppressions
|
12 |
+
warnings.filterwarnings('ignore', category=UserWarning)
|
13 |
+
warnings.filterwarnings('ignore', category=DeprecationWarning)
|
14 |
+
warnings.filterwarnings('ignore', category=FutureWarning)
|
15 |
+
warnings.filterwarnings('ignore', message='.*benefit from vacuuming.*')
|
16 |
+
warnings.filterwarnings('ignore', message='.*sparse_softmax_cross_entropy.*')
|
17 |
+
|
18 |
+
# Suppress all logging
|
19 |
+
logging.getLogger().setLevel(logging.ERROR)
|
20 |
+
# Suppress TensorFlow logging
|
21 |
+
logging.getLogger('tensorflow').setLevel(logging.ERROR)
|
22 |
+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
23 |
+
|
24 |
+
from osho_qa_service import get_answer_from_osho
|
25 |
+
|
26 |
+
if __name__ == "__main__":
|
27 |
+
# Example query
|
28 |
+
query = "What is the relationship between breath and consciousness?"
|
29 |
|
30 |
+
# Get answer using the service
|
31 |
+
response = get_answer_from_osho(query)
|
|
|
|
|
32 |
|
33 |
+
# Display formatted answer
|
34 |
+
print(f"\nQuery: {response['question']}\n")
|
|
|
|
|
|
|
35 |
|
36 |
+
# Get the first result as main answer
|
37 |
+
main_passage = response['answer_passages'][0]
|
38 |
+
print(f"I have discussed this idea in book '{main_passage['book']}':")
|
39 |
+
print(f"{main_passage['text']}\n")
|
|
|
40 |
|
41 |
+
# List other books as references
|
42 |
+
other_books = [p['book'] for p in response['answer_passages'][1:]]
|
43 |
+
if other_books:
|
44 |
+
print("You can refer to other books:", ", ".join(other_books))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
@@ -4,3 +4,4 @@ chromadb==0.4.20
|
|
4 |
sentence-transformers==2.2.2
|
5 |
tqdm==4.66.1
|
6 |
huggingface-hub==0.19.4
|
|
|
|
4 |
sentence-transformers==2.2.2
|
5 |
tqdm==4.66.1
|
6 |
huggingface-hub==0.19.4
|
7 |
+
streamlit==1.29.0
|
streamlit_app.py
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
|
4 |
+
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
|
5 |
+
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
6 |
+
|
7 |
+
import warnings
|
8 |
+
import logging
|
9 |
+
# Suppress all warnings
|
10 |
+
warnings.filterwarnings('ignore')
|
11 |
+
logging.getLogger().setLevel(logging.ERROR)
|
12 |
+
|
13 |
+
from osho_qa_service import get_answer_from_osho
|
14 |
+
|
15 |
+
# Set page config
|
16 |
+
st.set_page_config(
|
17 |
+
page_title="Ask Osho",
|
18 |
+
page_icon="π§ββοΈ",
|
19 |
+
layout="centered",
|
20 |
+
initial_sidebar_state="collapsed"
|
21 |
+
)
|
22 |
+
|
23 |
+
# Title and description
|
24 |
+
st.title("π§ββοΈ Ask Osho")
|
25 |
+
st.markdown("""
|
26 |
+
This application allows you to ask questions and receive answers from Osho's wisdom.
|
27 |
+
Choose from example questions or ask your own question.
|
28 |
+
""")
|
29 |
+
|
30 |
+
# Example questions
|
31 |
+
example_questions = [
|
32 |
+
"What is the relationship between breath and consciousness?",
|
33 |
+
"How can meditation help in daily life?",
|
34 |
+
"What is the difference between mind and consciousness?",
|
35 |
+
"What is the nature of love?",
|
36 |
+
"How can one find inner peace?"
|
37 |
+
]
|
38 |
+
|
39 |
+
# Initialize session state for question if not exists
|
40 |
+
if 'question' not in st.session_state:
|
41 |
+
st.session_state.question = ""
|
42 |
+
|
43 |
+
# Create columns for example questions
|
44 |
+
st.subheader("Example Questions")
|
45 |
+
cols = st.columns(3)
|
46 |
+
|
47 |
+
# Function to update question
|
48 |
+
def set_question(q):
|
49 |
+
st.session_state.question = q
|
50 |
+
|
51 |
+
# Create buttons for example questions
|
52 |
+
for i, question in enumerate(example_questions):
|
53 |
+
col_idx = i % 3
|
54 |
+
if cols[col_idx].button(f"Q{i+1}: {question[:30]}...", key=f"q{i}",
|
55 |
+
help=question): # Show full question on hover
|
56 |
+
set_question(question)
|
57 |
+
|
58 |
+
# Or ask your own question
|
59 |
+
st.subheader("Or Ask Your Own Question")
|
60 |
+
question = st.text_input("Type your question here:",
|
61 |
+
value=st.session_state.question,
|
62 |
+
key="question_input",
|
63 |
+
on_change=lambda: set_question(st.session_state.question_input))
|
64 |
+
|
65 |
+
# Answer button
|
66 |
+
if st.button("Please Answer Osho", type="primary", key="answer_button"):
|
67 |
+
if question:
|
68 |
+
with st.spinner("Seeking wisdom in Osho's teachings..."):
|
69 |
+
try:
|
70 |
+
# Get answer using the service
|
71 |
+
response = get_answer_from_osho(question)
|
72 |
+
|
73 |
+
# Display the answer in a nice box
|
74 |
+
st.markdown("---")
|
75 |
+
st.subheader("Osho's Answer")
|
76 |
+
|
77 |
+
# Main answer
|
78 |
+
main_passage = response['answer_passages'][0]
|
79 |
+
st.info(f"**From the book**: _{main_passage['book']}_")
|
80 |
+
st.markdown(main_passage['text'])
|
81 |
+
|
82 |
+
# Other references
|
83 |
+
other_books = [p['book'] for p in response['answer_passages'][1:]]
|
84 |
+
if other_books:
|
85 |
+
st.markdown("---")
|
86 |
+
st.success("**You can also explore these books:**")
|
87 |
+
for book in other_books:
|
88 |
+
st.markdown(f"- {book}")
|
89 |
+
except Exception as e:
|
90 |
+
st.error("Sorry, I encountered an error while processing your question. Please try again.")
|
91 |
+
st.error(f"Error details: {str(e)}")
|
92 |
+
else:
|
93 |
+
st.warning("Please enter a question or select an example question.")
|
94 |
+
|
95 |
+
# Add some styling
|
96 |
+
st.markdown("""
|
97 |
+
<style>
|
98 |
+
.stButton button {
|
99 |
+
width: 100%;
|
100 |
+
}
|
101 |
+
.stButton>button:first-child {
|
102 |
+
margin-top: 20px;
|
103 |
+
}
|
104 |
+
.stMarkdown {
|
105 |
+
text-align: justify;
|
106 |
+
}
|
107 |
+
</style>
|
108 |
+
""", unsafe_allow_html=True)
|