Spaces:
Sleeping
Sleeping
Prometheus v0.2. removed unused files, updated main app with logs, conversation db, and new UI
Browse files- app.py +256 -129
- logger.py +0 -0
- generator.py → logs/conversations.db +0 -0
- preprocess_curriculum.py +0 -132
- preprocess_textbook.py +0 -80
- processed/curriculum_chunks.json +0 -0
- retrieval_log.csv +0 -0
- retriever_logger.py +0 -113
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
# app.py
|
|
|
|
| 2 |
|
| 3 |
import streamlit as st
|
| 4 |
import sqlite3
|
|
@@ -6,25 +7,36 @@ from datetime import datetime
|
|
| 6 |
from retriever import Retriever
|
| 7 |
from openai import OpenAI
|
| 8 |
import logging
|
|
|
|
| 9 |
from transformers import pipeline
|
| 10 |
import tiktoken
|
|
|
|
| 11 |
|
| 12 |
# -----------------------
|
| 13 |
# Configuration and Setup
|
| 14 |
# -----------------------
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# Setup logging
|
| 17 |
logging.basicConfig(
|
| 18 |
level=logging.INFO,
|
| 19 |
-
format='%(asctime)s %(levelname)s:%(name)s:%(message)s',
|
| 20 |
handlers=[
|
| 21 |
-
|
| 22 |
logging.StreamHandler()
|
| 23 |
]
|
| 24 |
)
|
| 25 |
logger = logging.getLogger(__name__)
|
| 26 |
|
| 27 |
-
#
|
|
|
|
|
|
|
| 28 |
def load_curriculum(file_path):
|
| 29 |
"""
|
| 30 |
Reads the curriculum text file and returns its content as a string.
|
|
@@ -35,9 +47,12 @@ def load_curriculum(file_path):
|
|
| 35 |
Returns:
|
| 36 |
str: Contents of the text file.
|
| 37 |
"""
|
|
|
|
|
|
|
| 38 |
try:
|
| 39 |
with open(file_path, 'r', encoding='utf-8') as file:
|
| 40 |
content = file.read().strip()
|
|
|
|
| 41 |
return content
|
| 42 |
except FileNotFoundError:
|
| 43 |
logger.error(f"The curriculum file '{file_path}' does not exist.")
|
|
@@ -46,12 +61,16 @@ def load_curriculum(file_path):
|
|
| 46 |
logger.error(f"Error reading the curriculum file: {e}")
|
| 47 |
return "An error occurred while loading the curriculum."
|
| 48 |
|
|
|
|
| 49 |
CURRICULUM_FILE_PATH = './data/curriculum.txt'
|
|
|
|
| 50 |
CURRICULUM_SUMMARY = load_curriculum(CURRICULUM_FILE_PATH)
|
|
|
|
| 51 |
|
|
|
|
| 52 |
MODEL_NAME = "gpt-4o-mini"
|
| 53 |
-
TOP_K = 3
|
| 54 |
-
DB_NAME = "conversations.db"
|
| 55 |
|
| 56 |
# -----------------------
|
| 57 |
# Helper Functions
|
|
@@ -59,15 +78,22 @@ DB_NAME = "conversations.db"
|
|
| 59 |
|
| 60 |
def init_db():
|
| 61 |
"""Initialize the SQLite database if it doesn't exist."""
|
|
|
|
| 62 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
conn = sqlite3.connect(DB_NAME)
|
| 64 |
c = conn.cursor()
|
| 65 |
c.execute('''
|
| 66 |
CREATE TABLE IF NOT EXISTS conversations (
|
| 67 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 68 |
-
role TEXT,
|
| 69 |
-
content TEXT,
|
| 70 |
-
timestamp TEXT
|
| 71 |
)
|
| 72 |
''')
|
| 73 |
conn.commit()
|
|
@@ -76,64 +102,116 @@ def init_db():
|
|
| 76 |
logger.error(f"Error initializing database: {e}")
|
| 77 |
raise
|
| 78 |
finally:
|
| 79 |
-
conn
|
|
|
|
|
|
|
| 80 |
|
| 81 |
def add_message(role, content):
|
| 82 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
try:
|
| 84 |
with sqlite3.connect(DB_NAME) as conn:
|
| 85 |
c = conn.cursor()
|
|
|
|
|
|
|
| 86 |
c.execute("INSERT INTO conversations (role, content, timestamp) VALUES (?, ?, ?)",
|
| 87 |
(role, content, datetime.now().isoformat()))
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
except sqlite3.Error as e:
|
| 90 |
logger.error(f"Error adding message to database: {e}")
|
| 91 |
raise
|
| 92 |
|
| 93 |
|
| 94 |
def load_messages():
|
| 95 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
try:
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
| 104 |
except sqlite3.Error as e:
|
| 105 |
logger.error(f"Error loading messages from database: {e}")
|
| 106 |
raise
|
| 107 |
-
|
| 108 |
-
conn.close()
|
| 109 |
|
| 110 |
@st.cache_resource
|
| 111 |
def load_summarizer():
|
| 112 |
"""
|
| 113 |
Load and cache the summarization pipeline.
|
|
|
|
| 114 |
"""
|
| 115 |
try:
|
|
|
|
|
|
|
|
|
|
| 116 |
summarizer = pipeline("summarization", model="facebook/bart-large-cnn", device=-1)
|
|
|
|
|
|
|
| 117 |
return summarizer
|
| 118 |
except Exception as e:
|
| 119 |
logger.error(f"Failed to load summarizer pipeline: {e}")
|
|
|
|
| 120 |
return None
|
| 121 |
|
|
|
|
| 122 |
summarizer = load_summarizer()
|
| 123 |
|
| 124 |
-
|
|
|
|
| 125 |
"""
|
| 126 |
If conversation too long, summarize older messages.
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
"""
|
| 129 |
-
if len(messages)
|
| 130 |
-
return messages # No need to summarize
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
# Combine older messages
|
| 137 |
conversation_text = "\n".join([f"{m['role']}: {m['content']}" for m in older])
|
| 138 |
summary_input = ("Summarize the following conversation concisely to act as assistant's memory:\n\n"
|
| 139 |
+ conversation_text)
|
|
@@ -141,83 +219,57 @@ def truncate_and_summarize(messages):
|
|
| 141 |
if summarizer:
|
| 142 |
try:
|
| 143 |
# Perform summarization
|
| 144 |
-
|
|
|
|
| 145 |
summary_text = summary_result[0]['summary_text'].strip()
|
| 146 |
logger.info("Successfully summarized older conversation.")
|
|
|
|
|
|
|
| 147 |
summarized = [{"role": "system", "content": "Summary of previous conversation: " + summary_text}]
|
| 148 |
return summarized + recent
|
| 149 |
except Exception as e:
|
| 150 |
logger.error(f"Error during summarization: {e}")
|
|
|
|
| 151 |
|
|
|
|
| 152 |
return messages
|
| 153 |
|
|
|
|
| 154 |
def build_prompt(user_query, retrieved_chunks, messages):
|
| 155 |
"""
|
| 156 |
Build the prompt for the LLM:
|
| 157 |
-
- Include
|
| 158 |
- Include the curriculum summary
|
| 159 |
- Summarize older conversation history
|
| 160 |
- Add retrieved chunks as system context
|
| 161 |
- Include user query at the end
|
| 162 |
"""
|
|
|
|
|
|
|
| 163 |
# Summarize older messages if needed
|
| 164 |
messages = truncate_and_summarize(messages)
|
| 165 |
|
| 166 |
-
#
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
Your role is to facilitate a balanced learning experience by presenting questions that allow students to form their own opinions based on evidence and logic. Avoid offering personal or ideological viewpoints. Instead, your questioning should promote open inquiry, encouraging students to explore diverse perspectives while grounding their conclusions in facts.
|
| 178 |
-
◦ Example: For a topic like climate change, you might ask, “What are the different scientific perspectives on climate change, and what evidence supports each viewpoint?” This invites students to examine the topic through multiple lenses without pushing a particular viewpoint.
|
| 179 |
-
3. Respect TDSB's Inclusive Standards:
|
| 180 |
-
While maintaining neutrality, adhere to the TDSB's commitment to inclusivity. Your questions should create a safe, respectful space for all learners, encouraging critical thinking and constructive dialogue. Avoid introducing any biases, and ensure that all students are engaged in a fair and supportive learning process.
|
| 181 |
-
4. Promote Merit-Based Learning and Intellectual Effort:
|
| 182 |
-
Your approach should emphasize the importance of hard work and intellectual effort. Encourage students to engage rigorously with the material and to approach learning as a process of discovery. Your questions should be designed to push students intellectually, encouraging resilience, self-exploration, and persistence.
|
| 183 |
-
◦ Example: If a student finds a concept challenging, instead of giving them the answer, ask, “What strategies have you considered so far to understand this topic? What might you try next?” This approach encourages perseverance and a problem-solving mindset.
|
| 184 |
-
5. Reinforce the Meritocratic Framework:
|
| 185 |
-
In every interaction, ensure that students understand that academic success comes from effort and critical engagement. Your questioning should promote an equal learning environment where all students are guided to think deeply, work diligently, and achieve understanding based on their commitment and reasoning skills.
|
| 186 |
-
|
| 187 |
-
Process for Engaging Students Using the Socratic Method:
|
| 188 |
-
1. Understand the Student's Inquiry:
|
| 189 |
-
Begin each interaction by analyzing the student's question. Identify any assumptions or gaps in their understanding, and structure your response to address these areas with questions that guide them toward clarity.
|
| 190 |
-
2. Formulate Thought-Provoking Questions:
|
| 191 |
-
Craft questions that encourage critical thinking and self-reflection. Tailor your responses to be intellectually stimulating while remaining supportive. Your questions should help the student uncover layers of complexity within the topic.
|
| 192 |
-
◦ Example Question Formats:
|
| 193 |
-
▪ “What factors do you think influenced this outcome?”
|
| 194 |
-
▪ “How would you apply this concept to a different situation?”
|
| 195 |
-
▪ “What are some alternative explanations for this phenomenon?”
|
| 196 |
-
▪ “If you were to explain this to someone else, how would you start?”
|
| 197 |
-
3. Encourage Reflection and Ongoing Inquiry:
|
| 198 |
-
Once the student responds to your initial question, continue guiding them with follow-up questions. Foster a process of continuous reflection, helping them to dig deeper and connect various ideas. Your role is to keep the conversation open-ended, allowing the student to reach new insights through exploration.
|
| 199 |
-
4. Adapt Questions to Student's Level and Sentiment:
|
| 200 |
-
Tailor your questions based on the student's comprehension level and emotional state. If the student is struggling, provide supportive, clarifying questions. For those excelling, offer more challenging prompts that push their intellectual limits. Always ensure that your approach respects the Socratic principle of guiding rather than providing answers.
|
| 201 |
-
|
| 202 |
-
Example of Prometheus 1 in Action:
|
| 203 |
-
Student Question:
|
| 204 |
-
“Why is democracy considered a good system of government?”
|
| 205 |
-
Prometheus 1 Response:
|
| 206 |
-
“Rather than focusing on whether it's good or not, what are some features of democracy that appeal to you? How might these features compare to those in other systems of government?”
|
| 207 |
-
This response encourages the student to reflect on democratic principles, fostering critical thinking without imposing a definitive answer.
|
| 208 |
-
|
| 209 |
-
Conclusion:
|
| 210 |
-
Prometheus 1, you are the intellectual guide of the neural network, using the Socratic method to promote deep thinking and independent reasoning. Your questions are designed to foster a learning environment in line with TDSB's standards, emphasizing meritocracy, neutrality, and critical inquiry. Through your guidance, students develop a comprehensive understanding of the material, driven by their own curiosity and intellectual effort.
|
| 211 |
-
"""
|
| 212 |
|
| 213 |
# Add the Socratic guide to the prompt
|
| 214 |
-
prompt_messages
|
| 215 |
-
|
| 216 |
-
|
|
|
|
| 217 |
|
| 218 |
# Include the curriculum summary
|
| 219 |
curriculum_instructions = f"""
|
| 220 |
-
Here are the learning goals for this class based on the
|
| 221 |
{CURRICULUM_SUMMARY}
|
| 222 |
"""
|
| 223 |
prompt_messages.append({"role": "system", "content": curriculum_instructions})
|
|
@@ -229,42 +281,112 @@ def build_prompt(user_query, retrieved_chunks, messages):
|
|
| 229 |
# Add retrieved chunks as system context
|
| 230 |
if retrieved_chunks:
|
| 231 |
chunks_text = "\n".join([f"Page {c['page_num']}:\n{c['content']}" for c in retrieved_chunks])
|
| 232 |
-
prompt_messages.append({
|
|
|
|
|
|
|
|
|
|
| 233 |
|
| 234 |
# Add the user's query
|
| 235 |
prompt_messages.append({"role": "user", "content": user_query})
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
return prompt_messages
|
| 238 |
|
| 239 |
|
|
|
|
| 240 |
def count_tokens(messages, encoding_name="o200k_base"):
|
| 241 |
-
|
| 242 |
-
tokens
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
|
| 249 |
def send_query_to_llm(messages):
|
| 250 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
try:
|
| 252 |
# Count input tokens
|
| 253 |
-
|
| 254 |
-
logger.info(f"Input prompt tokens: {
|
|
|
|
| 255 |
|
|
|
|
| 256 |
client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
|
|
|
|
|
|
|
|
|
|
| 257 |
completion = client.chat.completions.create(
|
| 258 |
model=MODEL_NAME,
|
| 259 |
messages=messages
|
| 260 |
)
|
|
|
|
|
|
|
| 261 |
assistant_response = completion.choices[0].message.content
|
|
|
|
| 262 |
|
| 263 |
# Count output tokens
|
| 264 |
-
|
| 265 |
-
logger.info(f"
|
| 266 |
|
| 267 |
return assistant_response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
except Exception as e:
|
| 269 |
logger.error(f"Error communicating with OpenAI: {e}")
|
| 270 |
return "I'm sorry, I couldn't process your request at the moment."
|
|
@@ -288,32 +410,28 @@ def load_retriever():
|
|
| 288 |
|
| 289 |
retriever = load_retriever()
|
| 290 |
|
| 291 |
-
st.title("Prometheus v0.
|
| 292 |
|
| 293 |
-
|
| 294 |
-
st.
|
| 295 |
-
st.write(
|
| 296 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
|
| 298 |
-
#
|
|
|
|
| 299 |
messages = load_messages()
|
| 300 |
for m in messages:
|
| 301 |
-
|
| 302 |
-
st.markdown(
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
# Input form
|
| 309 |
-
with st.form(key='query_form'):
|
| 310 |
-
user_query = st.text_area("Enter your query:", height=100, key='user_input')
|
| 311 |
-
submitted = st.form_submit_button("Send")
|
| 312 |
-
|
| 313 |
-
if submitted and user_query.strip():
|
| 314 |
-
# If user wants to quit
|
| 315 |
-
if user_query.strip().lower() == 'quit':
|
| 316 |
-
# Clear conversation history
|
| 317 |
try:
|
| 318 |
conn = sqlite3.connect(DB_NAME)
|
| 319 |
c = conn.cursor()
|
|
@@ -328,12 +446,12 @@ if submitted and user_query.strip():
|
|
| 328 |
conn.close()
|
| 329 |
else:
|
| 330 |
# Add user message to DB
|
| 331 |
-
add_message("user",
|
| 332 |
|
| 333 |
# Retrieve chunks
|
| 334 |
if retriever:
|
| 335 |
-
results = retriever.retrieve(
|
| 336 |
-
logger.info(f"Retrieved {len(results)} chunks for query: '{
|
| 337 |
else:
|
| 338 |
results = []
|
| 339 |
logger.warning("Retriever is not available.")
|
|
@@ -342,23 +460,32 @@ if submitted and user_query.strip():
|
|
| 342 |
messages = load_messages()
|
| 343 |
|
| 344 |
# Build prompt
|
| 345 |
-
llm_prompt = build_prompt(
|
| 346 |
|
| 347 |
# Call LLM
|
| 348 |
assistant_response = send_query_to_llm(llm_prompt)
|
| 349 |
|
| 350 |
-
# Add assistant
|
| 351 |
add_message("assistant", assistant_response)
|
| 352 |
|
| 353 |
-
# Display assistant response
|
| 354 |
-
st.
|
|
|
|
| 355 |
|
|
|
|
| 356 |
if results:
|
| 357 |
-
st.
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
else:
|
| 362 |
-
st.
|
| 363 |
|
| 364 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
# v0.2
|
| 3 |
|
| 4 |
import streamlit as st
|
| 5 |
import sqlite3
|
|
|
|
| 7 |
from retriever import Retriever
|
| 8 |
from openai import OpenAI
|
| 9 |
import logging
|
| 10 |
+
from logging.handlers import RotatingFileHandler
|
| 11 |
from transformers import pipeline
|
| 12 |
import tiktoken
|
| 13 |
+
import os
|
| 14 |
|
| 15 |
# -----------------------
|
| 16 |
# Configuration and Setup
|
| 17 |
# -----------------------
|
| 18 |
|
| 19 |
+
# Ensure the log file exists
|
| 20 |
+
LOG_FILE_PATH = "./logs/app.log"
|
| 21 |
+
|
| 22 |
+
if not os.path.exists(LOG_FILE_PATH):
|
| 23 |
+
with open(LOG_FILE_PATH, 'w') as log_file:
|
| 24 |
+
log_file.write("") # Create an empty file
|
| 25 |
+
|
| 26 |
# Setup logging
|
| 27 |
logging.basicConfig(
|
| 28 |
level=logging.INFO,
|
| 29 |
+
format='%(asctime)s %(levelname)s:%(name)s:%(funcName)s:%(message)s',
|
| 30 |
handlers=[
|
| 31 |
+
RotatingFileHandler(LOG_FILE_PATH, maxBytes=5*1024*1024, backupCount=3),
|
| 32 |
logging.StreamHandler()
|
| 33 |
]
|
| 34 |
)
|
| 35 |
logger = logging.getLogger(__name__)
|
| 36 |
|
| 37 |
+
# Test logging
|
| 38 |
+
logger.info(f"Logging setup initialized successfully at {datetime.now().isoformat()}.")
|
| 39 |
+
|
| 40 |
def load_curriculum(file_path):
|
| 41 |
"""
|
| 42 |
Reads the curriculum text file and returns its content as a string.
|
|
|
|
| 47 |
Returns:
|
| 48 |
str: Contents of the text file.
|
| 49 |
"""
|
| 50 |
+
logger.info(f"Attempting to load curriculum from: {file_path}")
|
| 51 |
+
|
| 52 |
try:
|
| 53 |
with open(file_path, 'r', encoding='utf-8') as file:
|
| 54 |
content = file.read().strip()
|
| 55 |
+
logger.info(f"Successfully loaded curriculum. Content length: {len(content)} characters.")
|
| 56 |
return content
|
| 57 |
except FileNotFoundError:
|
| 58 |
logger.error(f"The curriculum file '{file_path}' does not exist.")
|
|
|
|
| 61 |
logger.error(f"Error reading the curriculum file: {e}")
|
| 62 |
return "An error occurred while loading the curriculum."
|
| 63 |
|
| 64 |
+
# Define curriculum file path and load summary
|
| 65 |
CURRICULUM_FILE_PATH = './data/curriculum.txt'
|
| 66 |
+
logger.info(f"Initializing curriculum loading from path: {CURRICULUM_FILE_PATH}")
|
| 67 |
CURRICULUM_SUMMARY = load_curriculum(CURRICULUM_FILE_PATH)
|
| 68 |
+
logger.info("Curriculum loading complete.")
|
| 69 |
|
| 70 |
+
# Set up model, retriever chunks, conversation db
|
| 71 |
MODEL_NAME = "gpt-4o-mini"
|
| 72 |
+
TOP_K = 3 # number of chunks to retrieve
|
| 73 |
+
DB_NAME = "./logs/conversations.db"
|
| 74 |
|
| 75 |
# -----------------------
|
| 76 |
# Helper Functions
|
|
|
|
| 78 |
|
| 79 |
def init_db():
|
| 80 |
"""Initialize the SQLite database if it doesn't exist."""
|
| 81 |
+
logger.info(f"Initializing database at: {DB_NAME}")
|
| 82 |
try:
|
| 83 |
+
# Ensure database file exists
|
| 84 |
+
if not os.path.exists(DB_NAME):
|
| 85 |
+
logger.info(f"{DB_NAME} not found. Creating a new database file.")
|
| 86 |
+
open(DB_NAME, 'w').close() # Create an empty file
|
| 87 |
+
|
| 88 |
+
# Connect to the database and initialize the table
|
| 89 |
conn = sqlite3.connect(DB_NAME)
|
| 90 |
c = conn.cursor()
|
| 91 |
c.execute('''
|
| 92 |
CREATE TABLE IF NOT EXISTS conversations (
|
| 93 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 94 |
+
role TEXT NOT NULL,
|
| 95 |
+
content TEXT NOT NULL,
|
| 96 |
+
timestamp TEXT NOT NULL
|
| 97 |
)
|
| 98 |
''')
|
| 99 |
conn.commit()
|
|
|
|
| 102 |
logger.error(f"Error initializing database: {e}")
|
| 103 |
raise
|
| 104 |
finally:
|
| 105 |
+
if 'conn' in locals():
|
| 106 |
+
conn.close()
|
| 107 |
+
logger.info("Database connection closed.")
|
| 108 |
|
| 109 |
def add_message(role, content):
|
| 110 |
+
"""
|
| 111 |
+
Add a message (user/assistant) to the database.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
role (str): Role of the message sender (e.g., 'user', 'assistant').
|
| 115 |
+
content (str): Content of the message.
|
| 116 |
+
"""
|
| 117 |
+
logger.info(f"Attempting to add a message: role={role}, content length={len(content)}")
|
| 118 |
+
|
| 119 |
+
# Validate inputs
|
| 120 |
+
if not role or not isinstance(role, str):
|
| 121 |
+
logger.error("Invalid role provided. Must be a non-empty string.")
|
| 122 |
+
raise ValueError("Role must be a non-empty string.")
|
| 123 |
+
if not content or not isinstance(content, str):
|
| 124 |
+
logger.error("Invalid content provided. Must be a non-empty string.")
|
| 125 |
+
raise ValueError("Content must be a non-empty string.")
|
| 126 |
+
|
| 127 |
try:
|
| 128 |
with sqlite3.connect(DB_NAME) as conn:
|
| 129 |
c = conn.cursor()
|
| 130 |
+
|
| 131 |
+
# Insert the message
|
| 132 |
c.execute("INSERT INTO conversations (role, content, timestamp) VALUES (?, ?, ?)",
|
| 133 |
(role, content, datetime.now().isoformat()))
|
| 134 |
+
conn.commit()
|
| 135 |
+
|
| 136 |
+
# Retrieve the ID of the inserted row
|
| 137 |
+
message_id = c.lastrowid
|
| 138 |
+
logger.info(f"Message successfully added: id={message_id}, role={role}, content length={len(content)}")
|
| 139 |
except sqlite3.Error as e:
|
| 140 |
logger.error(f"Error adding message to database: {e}")
|
| 141 |
raise
|
| 142 |
|
| 143 |
|
| 144 |
def load_messages():
|
| 145 |
+
"""
|
| 146 |
+
Load all messages from the database.
|
| 147 |
+
|
| 148 |
+
Returns:
|
| 149 |
+
list: A list of dictionaries with each message's role and content.
|
| 150 |
+
"""
|
| 151 |
+
logger.info("Attempting to load messages from the database.")
|
| 152 |
+
|
| 153 |
try:
|
| 154 |
+
with sqlite3.connect(DB_NAME) as conn:
|
| 155 |
+
c = conn.cursor()
|
| 156 |
+
c.execute("SELECT role, content FROM conversations ORDER BY id ASC")
|
| 157 |
+
rows = c.fetchall()
|
| 158 |
+
|
| 159 |
+
# Transform rows into a list of dictionaries
|
| 160 |
+
messages = [{"role": r, "content": cnt} for (r, cnt) in rows]
|
| 161 |
+
logger.info(f"Successfully loaded {len(messages)} messages from the database.")
|
| 162 |
+
return messages
|
| 163 |
except sqlite3.Error as e:
|
| 164 |
logger.error(f"Error loading messages from database: {e}")
|
| 165 |
raise
|
| 166 |
+
|
|
|
|
| 167 |
|
| 168 |
@st.cache_resource
|
| 169 |
def load_summarizer():
|
| 170 |
"""
|
| 171 |
Load and cache the summarization pipeline.
|
| 172 |
+
Designed for a CPU-only environment and uses Hugging Face-hosted models.
|
| 173 |
"""
|
| 174 |
try:
|
| 175 |
+
logger.info("Loading summarizer model on CPU...")
|
| 176 |
+
|
| 177 |
+
# Initialize summarization pipeline on CPU
|
| 178 |
summarizer = pipeline("summarization", model="facebook/bart-large-cnn", device=-1)
|
| 179 |
+
|
| 180 |
+
logger.info("Summarizer model loaded successfully.")
|
| 181 |
return summarizer
|
| 182 |
except Exception as e:
|
| 183 |
logger.error(f"Failed to load summarizer pipeline: {e}")
|
| 184 |
+
st.error("The summarization model could not be loaded. Please try again later.")
|
| 185 |
return None
|
| 186 |
|
| 187 |
+
# Load summarizer model
|
| 188 |
summarizer = load_summarizer()
|
| 189 |
|
| 190 |
+
|
| 191 |
+
def truncate_and_summarize(messages, max_length=2500, min_length=250, recent_messages=20):
|
| 192 |
"""
|
| 193 |
If conversation too long, summarize older messages.
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
messages (list): List of message dictionaries.
|
| 197 |
+
max_length (int): Maximum length for the summary.
|
| 198 |
+
min_length (int): Minimum length for the summary.
|
| 199 |
+
recent_messages (int): Number of recent messages to keep intact.
|
| 200 |
+
|
| 201 |
+
Returns:
|
| 202 |
+
list: Updated list of messages with older ones summarized.
|
| 203 |
"""
|
| 204 |
+
logger.info(f"Checking if summarization is needed. Total messages: {len(messages)}")
|
|
|
|
| 205 |
|
| 206 |
+
if len(messages) <= recent_messages:
|
| 207 |
+
logger.info("No summarization needed; message count within limit.")
|
| 208 |
+
return messages
|
| 209 |
+
|
| 210 |
+
# Split older and recent messages
|
| 211 |
+
older = messages[:-recent_messages]
|
| 212 |
+
recent = messages[-recent_messages:]
|
| 213 |
|
| 214 |
+
# Combine older messages
|
| 215 |
conversation_text = "\n".join([f"{m['role']}: {m['content']}" for m in older])
|
| 216 |
summary_input = ("Summarize the following conversation concisely to act as assistant's memory:\n\n"
|
| 217 |
+ conversation_text)
|
|
|
|
| 219 |
if summarizer:
|
| 220 |
try:
|
| 221 |
# Perform summarization
|
| 222 |
+
logger.info("Performing summarization of older messages.")
|
| 223 |
+
summary_result = summarizer(summary_input, max_length=max_length, min_length=min_length, do_sample=False)
|
| 224 |
summary_text = summary_result[0]['summary_text'].strip()
|
| 225 |
logger.info("Successfully summarized older conversation.")
|
| 226 |
+
|
| 227 |
+
# Prepend the summarized message
|
| 228 |
summarized = [{"role": "system", "content": "Summary of previous conversation: " + summary_text}]
|
| 229 |
return summarized + recent
|
| 230 |
except Exception as e:
|
| 231 |
logger.error(f"Error during summarization: {e}")
|
| 232 |
+
logger.warning("Returning messages without summarization.")
|
| 233 |
|
| 234 |
+
logger.warning("Summarizer not available. Returning messages without summarization.")
|
| 235 |
return messages
|
| 236 |
|
| 237 |
+
|
| 238 |
def build_prompt(user_query, retrieved_chunks, messages):
|
| 239 |
"""
|
| 240 |
Build the prompt for the LLM:
|
| 241 |
+
- Include system prompts from secrets
|
| 242 |
- Include the curriculum summary
|
| 243 |
- Summarize older conversation history
|
| 244 |
- Add retrieved chunks as system context
|
| 245 |
- Include user query at the end
|
| 246 |
"""
|
| 247 |
+
logger.info("Building prompt for the model.")
|
| 248 |
+
|
| 249 |
# Summarize older messages if needed
|
| 250 |
messages = truncate_and_summarize(messages)
|
| 251 |
|
| 252 |
+
# Load system prompts from secrets
|
| 253 |
+
try:
|
| 254 |
+
socratic_guide = st.secrets["SOCRATIC_GUIDE"]
|
| 255 |
+
prometheus_prompt = st.secrets["PROMETHEUS_PROMPT"]
|
| 256 |
+
logger.info("Successfully loaded system prompts from secrets.")
|
| 257 |
+
except KeyError as e:
|
| 258 |
+
logger.error(f"Missing key in secrets.toml: {e}")
|
| 259 |
+
raise ValueError(f"Missing secret key: {e}")
|
| 260 |
+
|
| 261 |
+
# Initialize the prompt messages
|
| 262 |
+
prompt_messages = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
# Add the Socratic guide to the prompt
|
| 265 |
+
prompt_messages.append({"role": "system", "content": socratic_guide})
|
| 266 |
+
|
| 267 |
+
# Add the placeholder prompt to the prompt
|
| 268 |
+
prompt_messages.append({"role": "system", "content": prometheus_prompt})
|
| 269 |
|
| 270 |
# Include the curriculum summary
|
| 271 |
curriculum_instructions = f"""
|
| 272 |
+
Here are the learning goals for this class based on the TDSB's Curriculum. Ensure that your responses are aligned with these goals:\n
|
| 273 |
{CURRICULUM_SUMMARY}
|
| 274 |
"""
|
| 275 |
prompt_messages.append({"role": "system", "content": curriculum_instructions})
|
|
|
|
| 281 |
# Add retrieved chunks as system context
|
| 282 |
if retrieved_chunks:
|
| 283 |
chunks_text = "\n".join([f"Page {c['page_num']}:\n{c['content']}" for c in retrieved_chunks])
|
| 284 |
+
prompt_messages.append({
|
| 285 |
+
"role": "system",
|
| 286 |
+
"content": "Retrieved content from textbook. Base response on this as your guiding knowledge. Do not make assumptions - keep your responses based on this context as source of truth:\n" + chunks_text
|
| 287 |
+
})
|
| 288 |
|
| 289 |
# Add the user's query
|
| 290 |
prompt_messages.append({"role": "user", "content": user_query})
|
| 291 |
|
| 292 |
+
# Count tokens in the final prompt
|
| 293 |
+
try:
|
| 294 |
+
token_data = count_tokens(prompt_messages)
|
| 295 |
+
logger.info(f"Total tokens for prompt: {token_data['total']}")
|
| 296 |
+
logger.info(f"Token breakdown by role: {token_data['by_role']}")
|
| 297 |
+
except Exception as e:
|
| 298 |
+
logger.error(f"Error counting tokens: {e}")
|
| 299 |
+
raise ValueError("Failed to count tokens for the prompt.")
|
| 300 |
+
|
| 301 |
+
logger.info("Prompt successfully built.")
|
| 302 |
return prompt_messages
|
| 303 |
|
| 304 |
|
| 305 |
+
#Token counter
|
| 306 |
def count_tokens(messages, encoding_name="o200k_base"):
|
| 307 |
+
"""
|
| 308 |
+
Count the total number of tokens in a list of messages, including system prompts.
|
| 309 |
+
|
| 310 |
+
Args:
|
| 311 |
+
messages (list): List of message dictionaries with 'role' and 'content' keys.
|
| 312 |
+
encoding_name (str): Encoding name for tokenization (default: "o200k_base").
|
| 313 |
+
|
| 314 |
+
Returns:
|
| 315 |
+
dict: Dictionary containing the total token count and a breakdown by role.
|
| 316 |
+
"""
|
| 317 |
+
try:
|
| 318 |
+
enc = tiktoken.get_encoding(encoding_name)
|
| 319 |
+
logger.info(f"Using encoding: {encoding_name}")
|
| 320 |
+
except Exception as e:
|
| 321 |
+
logger.error(f"Failed to get encoding '{encoding_name}': {e}")
|
| 322 |
+
raise ValueError(f"Invalid encoding: {encoding_name}")
|
| 323 |
+
|
| 324 |
+
total_tokens = 0
|
| 325 |
+
token_breakdown = {}
|
| 326 |
+
|
| 327 |
+
try:
|
| 328 |
+
for m in messages:
|
| 329 |
+
if not isinstance(m, dict) or "role" not in m or "content" not in m:
|
| 330 |
+
logger.error(f"Invalid message format: {m}")
|
| 331 |
+
raise ValueError("Each message must be a dictionary with 'role' and 'content' keys.")
|
| 332 |
+
|
| 333 |
+
# Encode role and content
|
| 334 |
+
role_tokens = len(enc.encode(m["role"]))
|
| 335 |
+
content_tokens = len(enc.encode(m["content"]))
|
| 336 |
+
message_tokens = role_tokens + content_tokens
|
| 337 |
+
|
| 338 |
+
# Add to totals
|
| 339 |
+
total_tokens += message_tokens
|
| 340 |
+
token_breakdown[m["role"]] = token_breakdown.get(m["role"], 0) + message_tokens
|
| 341 |
+
|
| 342 |
+
logger.info(f"Token count completed. Total tokens: {total_tokens}")
|
| 343 |
+
logger.info(f"Token breakdown by role: {token_breakdown}")
|
| 344 |
+
return {"total": total_tokens, "by_role": token_breakdown}
|
| 345 |
+
except Exception as e:
|
| 346 |
+
logger.error(f"Error counting tokens: {e}")
|
| 347 |
+
raise
|
| 348 |
+
|
| 349 |
|
| 350 |
def send_query_to_llm(messages):
|
| 351 |
+
"""
|
| 352 |
+
Send the constructed messages to the LLM and get a response.
|
| 353 |
+
|
| 354 |
+
Args:
|
| 355 |
+
messages (list): List of dictionaries forming the prompt for the LLM.
|
| 356 |
+
|
| 357 |
+
Returns:
|
| 358 |
+
str: The assistant's response or a fallback message if an error occurs.
|
| 359 |
+
"""
|
| 360 |
try:
|
| 361 |
# Count input tokens
|
| 362 |
+
token_data = count_tokens(messages, "o200k_base")
|
| 363 |
+
logger.info(f"Input prompt tokens: {token_data['total']}")
|
| 364 |
+
logger.info(f"Token breakdown (input): {token_data['by_role']}")
|
| 365 |
|
| 366 |
+
# Initialize OpenAI client
|
| 367 |
client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
|
| 368 |
+
|
| 369 |
+
# Send prompt to LLM
|
| 370 |
+
logger.info(f"Sending query to model: {MODEL_NAME}")
|
| 371 |
completion = client.chat.completions.create(
|
| 372 |
model=MODEL_NAME,
|
| 373 |
messages=messages
|
| 374 |
)
|
| 375 |
+
|
| 376 |
+
# Extract assistant's response
|
| 377 |
assistant_response = completion.choices[0].message.content
|
| 378 |
+
logger.info(f"Assistant response: {assistant_response}")
|
| 379 |
|
| 380 |
# Count output tokens
|
| 381 |
+
output_token_data = count_tokens([{"role": "assistant", "content": assistant_response}], "o200k_base")
|
| 382 |
+
logger.info(f"Assistant response output tokens: {output_token_data['total']}")
|
| 383 |
|
| 384 |
return assistant_response
|
| 385 |
+
|
| 386 |
+
except KeyError as e:
|
| 387 |
+
logger.error(f"Missing key in secrets or configuration: {e}")
|
| 388 |
+
return "Configuration error: Missing required API key or settings."
|
| 389 |
+
|
| 390 |
except Exception as e:
|
| 391 |
logger.error(f"Error communicating with OpenAI: {e}")
|
| 392 |
return "I'm sorry, I couldn't process your request at the moment."
|
|
|
|
| 410 |
|
| 411 |
retriever = load_retriever()
|
| 412 |
|
| 413 |
+
st.title("Prometheus v0.2 - Personal Tutor")
|
| 414 |
|
| 415 |
+
# Instructions
|
| 416 |
+
with st.expander("📋 Instructions", expanded=True):
|
| 417 |
+
st.write(
|
| 418 |
+
"""
|
| 419 |
+
- Press **Enter** to submit your query.
|
| 420 |
+
- Type **'quit'** to clear the conversation history.
|
| 421 |
+
"""
|
| 422 |
+
)
|
| 423 |
|
| 424 |
+
# Chat-like UI for conversation history
|
| 425 |
+
st.subheader("💬 Conversation History")
|
| 426 |
messages = load_messages()
|
| 427 |
for m in messages:
|
| 428 |
+
with st.chat_message(m['role']):
|
| 429 |
+
st.markdown(m['content'])
|
| 430 |
+
|
| 431 |
+
# Input area for user query
|
| 432 |
+
if prompt := st.chat_input("Ask Prometheus..."):
|
| 433 |
+
# If user inputs 'quit', clear conversation history
|
| 434 |
+
if prompt.strip().lower() == 'quit':
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 435 |
try:
|
| 436 |
conn = sqlite3.connect(DB_NAME)
|
| 437 |
c = conn.cursor()
|
|
|
|
| 446 |
conn.close()
|
| 447 |
else:
|
| 448 |
# Add user message to DB
|
| 449 |
+
add_message("user", prompt.strip())
|
| 450 |
|
| 451 |
# Retrieve chunks
|
| 452 |
if retriever:
|
| 453 |
+
results = retriever.retrieve(prompt.strip(), k=TOP_K)
|
| 454 |
+
logger.info(f"Retrieved {len(results)} chunks for query: '{prompt.strip()}'")
|
| 455 |
else:
|
| 456 |
results = []
|
| 457 |
logger.warning("Retriever is not available.")
|
|
|
|
| 460 |
messages = load_messages()
|
| 461 |
|
| 462 |
# Build prompt
|
| 463 |
+
llm_prompt = build_prompt(prompt.strip(), results, messages)
|
| 464 |
|
| 465 |
# Call LLM
|
| 466 |
assistant_response = send_query_to_llm(llm_prompt)
|
| 467 |
|
| 468 |
+
# Add assistant response to DB
|
| 469 |
add_message("assistant", assistant_response)
|
| 470 |
|
| 471 |
+
# Display assistant response
|
| 472 |
+
with st.chat_message("assistant"):
|
| 473 |
+
st.markdown(assistant_response)
|
| 474 |
|
| 475 |
+
# Display retrieved sources
|
| 476 |
if results:
|
| 477 |
+
with st.expander("📖 Sources", expanded=True):
|
| 478 |
+
for i, res in enumerate(results):
|
| 479 |
+
st.markdown(f"- **Result {i+1}:** Page {res['page_num']}")
|
| 480 |
+
st.code(res['content'])
|
| 481 |
else:
|
| 482 |
+
st.warning("No relevant sources found.")
|
| 483 |
|
| 484 |
+
# Optional log viewer
|
| 485 |
+
with st.expander("📜 View Logs (Optional)", expanded=True):
|
| 486 |
+
try:
|
| 487 |
+
with open(LOG_FILE_PATH, 'r') as log_file:
|
| 488 |
+
logs = log_file.read()
|
| 489 |
+
st.text_area("Logs", logs, height=200, key="log_viewer", disabled=True)
|
| 490 |
+
except Exception as e:
|
| 491 |
+
st.warning(f"Unable to read logs: {e}")
|
logger.py
DELETED
|
File without changes
|
generator.py → logs/conversations.db
RENAMED
|
File without changes
|
preprocess_curriculum.py
DELETED
|
@@ -1,132 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import PyPDF2
|
| 3 |
-
import pytesseract
|
| 4 |
-
from pdf2image import convert_from_path
|
| 5 |
-
from PIL import Image
|
| 6 |
-
import nltk
|
| 7 |
-
import tiktoken
|
| 8 |
-
import json
|
| 9 |
-
|
| 10 |
-
nltk.download('punkt_tab')
|
| 11 |
-
|
| 12 |
-
def extract_text_from_page(pdf_path, page_num):
|
| 13 |
-
# page_num is 1-indexed
|
| 14 |
-
text = ''
|
| 15 |
-
# Try to extract text using PyPDF2
|
| 16 |
-
with open(pdf_path, 'rb') as file:
|
| 17 |
-
reader = PyPDF2.PdfReader(file)
|
| 18 |
-
num_pages = len(reader.pages)
|
| 19 |
-
if page_num < 1 or page_num > num_pages:
|
| 20 |
-
print(f"Page {page_num} is out of range.")
|
| 21 |
-
return ''
|
| 22 |
-
page = reader.pages[page_num - 1]
|
| 23 |
-
try:
|
| 24 |
-
page_text = page.extract_text()
|
| 25 |
-
if page_text and page_text.strip():
|
| 26 |
-
print(f"Text extracted from page {page_num} using PyPDF2.")
|
| 27 |
-
text = f"<PAGE {page_num}>\n{page_text}\n"
|
| 28 |
-
return text
|
| 29 |
-
else:
|
| 30 |
-
print(f"No text found on page {page_num} using PyPDF2.")
|
| 31 |
-
except Exception as e:
|
| 32 |
-
print(f"Error reading page {page_num} with PyPDF2: {e}")
|
| 33 |
-
|
| 34 |
-
# If no text was extracted, perform OCR
|
| 35 |
-
try:
|
| 36 |
-
print(f"Performing OCR on page {page_num}...")
|
| 37 |
-
images = convert_from_path(pdf_path, first_page=page_num, last_page=page_num, dpi=200)
|
| 38 |
-
if images:
|
| 39 |
-
image = images[0]
|
| 40 |
-
ocr_text = pytesseract.image_to_string(image)
|
| 41 |
-
if ocr_text and ocr_text.strip():
|
| 42 |
-
print(f"OCR text extracted from page {page_num}.")
|
| 43 |
-
text = f"<PAGE {page_num}>\n{ocr_text}\n"
|
| 44 |
-
else:
|
| 45 |
-
print(f"No text found on page {page_num} using OCR.")
|
| 46 |
-
else:
|
| 47 |
-
print(f"Failed to convert page {page_num} to image.")
|
| 48 |
-
except Exception as e:
|
| 49 |
-
print(f"Error performing OCR on page {page_num}: {e}")
|
| 50 |
-
|
| 51 |
-
return text
|
| 52 |
-
|
| 53 |
-
def split_into_chunks(text, max_tokens=512):
|
| 54 |
-
tokenizer = tiktoken.get_encoding('o200k_base')
|
| 55 |
-
sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
|
| 56 |
-
chunks = []
|
| 57 |
-
pages = text.split('<PAGE ')[1:]
|
| 58 |
-
print(f"Total number of pages processed: {len(pages)}")
|
| 59 |
-
for page in pages:
|
| 60 |
-
try:
|
| 61 |
-
page_num, page_content = page.split('>\n', 1)
|
| 62 |
-
sentences = sentence_tokenizer.tokenize(page_content)
|
| 63 |
-
current_chunk = ''
|
| 64 |
-
current_chunk_tokens = 0
|
| 65 |
-
for sentence in sentences:
|
| 66 |
-
tokens = tokenizer.encode(sentence)
|
| 67 |
-
sentence_token_count = len(tokens)
|
| 68 |
-
if current_chunk_tokens + sentence_token_count <= max_tokens:
|
| 69 |
-
current_chunk += ' ' + sentence
|
| 70 |
-
current_chunk_tokens += sentence_token_count
|
| 71 |
-
else:
|
| 72 |
-
# Save the current chunk
|
| 73 |
-
chunks.append({
|
| 74 |
-
'page_num': page_num.strip(),
|
| 75 |
-
'content': current_chunk.strip()
|
| 76 |
-
})
|
| 77 |
-
# Start a new chunk with the current sentence
|
| 78 |
-
current_chunk = sentence
|
| 79 |
-
current_chunk_tokens = sentence_token_count
|
| 80 |
-
if current_chunk.strip():
|
| 81 |
-
# Add any remaining text as a chunk
|
| 82 |
-
chunks.append({
|
| 83 |
-
'page_num': page_num.strip(),
|
| 84 |
-
'content': current_chunk.strip()
|
| 85 |
-
})
|
| 86 |
-
except Exception as e:
|
| 87 |
-
print(f"An error occurred while processing page {page_num.strip()}: {e}")
|
| 88 |
-
continue
|
| 89 |
-
print(f"Total number of chunks created: {len(chunks)}")
|
| 90 |
-
return chunks
|
| 91 |
-
|
| 92 |
-
if __name__ == '__main__':
|
| 93 |
-
data_dir = 'data/'
|
| 94 |
-
curriculum_pdf = 'curriculum.pdf' # Replace with your curriculum PDF filename
|
| 95 |
-
pdf_path = os.path.join(data_dir, curriculum_pdf)
|
| 96 |
-
|
| 97 |
-
# Define the page ranges you want to process
|
| 98 |
-
page_ranges = [
|
| 99 |
-
(3, 59),
|
| 100 |
-
(103, 148),
|
| 101 |
-
(167, 194)
|
| 102 |
-
]
|
| 103 |
-
|
| 104 |
-
# Create a list of all page numbers to process
|
| 105 |
-
pages_to_process = []
|
| 106 |
-
for start, end in page_ranges:
|
| 107 |
-
pages_to_process.extend(range(start, end + 1))
|
| 108 |
-
pages_to_process = sorted(set(pages_to_process))
|
| 109 |
-
print(f"Total number of pages to process: {len(pages_to_process)}")
|
| 110 |
-
|
| 111 |
-
total_text = ''
|
| 112 |
-
for page_num in pages_to_process:
|
| 113 |
-
page_text = extract_text_from_page(pdf_path, page_num)
|
| 114 |
-
if page_text:
|
| 115 |
-
total_text += page_text
|
| 116 |
-
else:
|
| 117 |
-
print(f"No text extracted from page {page_num}.")
|
| 118 |
-
|
| 119 |
-
if total_text:
|
| 120 |
-
# Split into chunks
|
| 121 |
-
chunks = split_into_chunks(total_text, max_tokens=512)
|
| 122 |
-
if chunks:
|
| 123 |
-
# Ensure the 'processed' directory exists
|
| 124 |
-
if not os.path.exists('processed'):
|
| 125 |
-
os.makedirs('processed')
|
| 126 |
-
with open('processed/curriculum_chunks.json', 'w', encoding='utf-8') as f:
|
| 127 |
-
json.dump(chunks, f, ensure_ascii=False, indent=4)
|
| 128 |
-
print(f"Processed and saved {len(chunks)} curriculum chunks.")
|
| 129 |
-
else:
|
| 130 |
-
print("No chunks were created.")
|
| 131 |
-
else:
|
| 132 |
-
print("No text extracted from the curriculum.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
preprocess_textbook.py
DELETED
|
@@ -1,80 +0,0 @@
|
|
| 1 |
-
import PyPDF2
|
| 2 |
-
import nltk
|
| 3 |
-
import tiktoken
|
| 4 |
-
import json
|
| 5 |
-
import os
|
| 6 |
-
|
| 7 |
-
# Ensure 'punkt' tokenizer data is downloaded
|
| 8 |
-
nltk.download('punkt_tab')
|
| 9 |
-
|
| 10 |
-
def pdf_to_text(pdf_path):
|
| 11 |
-
text = ''
|
| 12 |
-
with open(pdf_path, 'rb') as file:
|
| 13 |
-
reader = PyPDF2.PdfReader(file)
|
| 14 |
-
num_pages = len(reader.pages)
|
| 15 |
-
print(f"Total pages in PDF: {num_pages}")
|
| 16 |
-
for page_num, page in enumerate(reader.pages):
|
| 17 |
-
page_text = page.extract_text()
|
| 18 |
-
if page_text:
|
| 19 |
-
text += f"<PAGE {page_num+1}>\n{page_text}\n"
|
| 20 |
-
else:
|
| 21 |
-
print(f"Warning: No text extracted from page {page_num+1}")
|
| 22 |
-
return text
|
| 23 |
-
|
| 24 |
-
def split_into_chunks(text, max_tokens=512): #can play with max_tokens to get larger or smaller outputs
|
| 25 |
-
tokenizer = tiktoken.get_encoding('o200k_base')
|
| 26 |
-
# Load the pre-trained Punkt tokenizer for English
|
| 27 |
-
sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
|
| 28 |
-
chunks = []
|
| 29 |
-
pages = text.split('<PAGE ')[1:]
|
| 30 |
-
print(f"Total number of pages processed: {len(pages)}")
|
| 31 |
-
for page in pages:
|
| 32 |
-
try:
|
| 33 |
-
page_num, page_content = page.split('>\n', 1)
|
| 34 |
-
sentences = sentence_tokenizer.tokenize(page_content)
|
| 35 |
-
current_chunk = ''
|
| 36 |
-
current_chunk_tokens = 0
|
| 37 |
-
for sentence in sentences:
|
| 38 |
-
sentence_tokens = len(tokenizer.encode(sentence))
|
| 39 |
-
print(f"sentence tokens: {sentence_tokens}")
|
| 40 |
-
if current_chunk_tokens + sentence_tokens <= max_tokens:
|
| 41 |
-
current_chunk += ' ' + sentence
|
| 42 |
-
current_chunk_tokens += sentence_tokens
|
| 43 |
-
else:
|
| 44 |
-
# Save the current chunk
|
| 45 |
-
chunks.append({
|
| 46 |
-
'page_num': page_num.strip(),
|
| 47 |
-
'content': current_chunk.strip()
|
| 48 |
-
})
|
| 49 |
-
# Start a new chunk with the current sentence
|
| 50 |
-
current_chunk = sentence
|
| 51 |
-
current_chunk_tokens = sentence_tokens
|
| 52 |
-
if current_chunk.strip():
|
| 53 |
-
# Add any remaining text as a chunk
|
| 54 |
-
chunks.append({
|
| 55 |
-
'page_num': page_num.strip(),
|
| 56 |
-
'content': current_chunk.strip()
|
| 57 |
-
})
|
| 58 |
-
except Exception as e:
|
| 59 |
-
print(f"An error occurred while processing page {page_num.strip()}: {e}")
|
| 60 |
-
continue
|
| 61 |
-
print(f"Total number of chunks created: {len(chunks)}")
|
| 62 |
-
return chunks
|
| 63 |
-
|
| 64 |
-
if __name__ == '__main__':
|
| 65 |
-
pdf_path = 'data/textbook.pdf'
|
| 66 |
-
text = pdf_to_text(pdf_path)
|
| 67 |
-
if text:
|
| 68 |
-
print(f"Extracted text length: {len(text)}")
|
| 69 |
-
chunks = split_into_chunks(text)
|
| 70 |
-
if chunks:
|
| 71 |
-
# Ensure the 'processed' directory exists
|
| 72 |
-
if not os.path.exists('processed'):
|
| 73 |
-
os.makedirs('processed')
|
| 74 |
-
with open('processed/chunks.json', 'w', encoding='utf-8') as f:
|
| 75 |
-
json.dump(chunks, f, ensure_ascii=False, indent=4)
|
| 76 |
-
print(f"Total chunks created: {len(chunks)}")
|
| 77 |
-
else:
|
| 78 |
-
print("No chunks were created.")
|
| 79 |
-
else:
|
| 80 |
-
print("Text extraction failed.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
processed/curriculum_chunks.json
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
retrieval_log.csv
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
retriever_logger.py
DELETED
|
@@ -1,113 +0,0 @@
|
|
| 1 |
-
# retriever.py with logging included
|
| 2 |
-
import numpy as np
|
| 3 |
-
import faiss
|
| 4 |
-
import json
|
| 5 |
-
import csv
|
| 6 |
-
import os
|
| 7 |
-
from sentence_transformers import SentenceTransformer
|
| 8 |
-
|
| 9 |
-
class Retriever:
|
| 10 |
-
def __init__(self):
|
| 11 |
-
# Load the embeddings and metadata
|
| 12 |
-
try:
|
| 13 |
-
self.embeddings = np.load('processed/embeddings.npy')
|
| 14 |
-
with open('processed/metadata.json', 'r', encoding='utf-8') as f:
|
| 15 |
-
self.metadata = json.load(f)
|
| 16 |
-
except FileNotFoundError:
|
| 17 |
-
print("Embeddings and metadata not found. Please run 'build_vector_store.py' first.")
|
| 18 |
-
exit(1)
|
| 19 |
-
|
| 20 |
-
# Load the FAISS index
|
| 21 |
-
try:
|
| 22 |
-
self.index = faiss.read_index('processed/faiss_index.idx')
|
| 23 |
-
except FileNotFoundError:
|
| 24 |
-
print("FAISS index not found. Please run 'build_vector_store.py' first.")
|
| 25 |
-
exit(1)
|
| 26 |
-
|
| 27 |
-
# Initialize the sentence transformer model
|
| 28 |
-
model_name = 'all-mpnet-base-v2' # Ensure this matches the model used during indexing
|
| 29 |
-
try:
|
| 30 |
-
self.model = SentenceTransformer(model_name)
|
| 31 |
-
except Exception as e:
|
| 32 |
-
print(f"Error initializing SentenceTransformer model: {e}")
|
| 33 |
-
exit(1)
|
| 34 |
-
|
| 35 |
-
def retrieve(self, query, k=5, min_content_words=25):
|
| 36 |
-
# Generate embedding for the query
|
| 37 |
-
try:
|
| 38 |
-
query_embedding = self.model.encode([query]).astype('float32')
|
| 39 |
-
except Exception as e:
|
| 40 |
-
print(f"Error generating embedding for query: {e}")
|
| 41 |
-
# Search the FAISS index
|
| 42 |
-
# Retrieve more candidates to allow filtering
|
| 43 |
-
distances, indices = self.index.search(query_embedding, k * 2)
|
| 44 |
-
|
| 45 |
-
# Retrieve the corresponding chunks and filter out short ones
|
| 46 |
-
results = []
|
| 47 |
-
try:
|
| 48 |
-
for idx in indices[0]:
|
| 49 |
-
chunk = self.metadata[idx]
|
| 50 |
-
# Filter out chunks that are too short
|
| 51 |
-
if len(chunk['content'].split()) >= min_content_words:
|
| 52 |
-
results.append(chunk)
|
| 53 |
-
if len(results) >= k:
|
| 54 |
-
break
|
| 55 |
-
except Exception as e:
|
| 56 |
-
print(f"Error retrieving chunks: {e}")
|
| 57 |
-
|
| 58 |
-
# If not enough results after filtering, fill up with unfiltered chunks
|
| 59 |
-
if len(results) < k:
|
| 60 |
-
try:
|
| 61 |
-
for idx in indices[0]:
|
| 62 |
-
chunk = self.metadata[idx]
|
| 63 |
-
if chunk not in results:
|
| 64 |
-
results.append(chunk)
|
| 65 |
-
if len(results) >= k:
|
| 66 |
-
break
|
| 67 |
-
except Exception as e:
|
| 68 |
-
print(f"Error retrieving unfiltered chunks: {e}")
|
| 69 |
-
|
| 70 |
-
return results[:k]
|
| 71 |
-
|
| 72 |
-
if __name__ == '__main__':
|
| 73 |
-
retriever = Retriever()
|
| 74 |
-
top_k = 5
|
| 75 |
-
log_file = 'retrieval_log.csv'
|
| 76 |
-
|
| 77 |
-
# Check if log file exists
|
| 78 |
-
file_exists = os.path.isfile(log_file)
|
| 79 |
-
|
| 80 |
-
# Open the log file once and keep it open
|
| 81 |
-
try:
|
| 82 |
-
with open(log_file, mode='a', encoding='utf-8', newline='') as csvfile:
|
| 83 |
-
fieldnames = ['Query', 'Result Number', 'Page Number', 'Content']
|
| 84 |
-
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
| 85 |
-
|
| 86 |
-
# Write header only if file did not exist before
|
| 87 |
-
if not file_exists:
|
| 88 |
-
writer.writeheader()
|
| 89 |
-
|
| 90 |
-
while True:
|
| 91 |
-
sample_query = input("Enter your query (or type 'quit' to exit): ")
|
| 92 |
-
if sample_query.lower() == 'quit':
|
| 93 |
-
print("Exiting the program.")
|
| 94 |
-
break
|
| 95 |
-
|
| 96 |
-
results = retriever.retrieve(sample_query, k=top_k)
|
| 97 |
-
print(f"\nTop {top_k} results for the query: '{sample_query}'\n")
|
| 98 |
-
for i, res in enumerate(results):
|
| 99 |
-
print(f"Result {i+1}:")
|
| 100 |
-
print(f"Page Number: {res['page_num']}")
|
| 101 |
-
print(f"Content: {res['content']}\n")
|
| 102 |
-
|
| 103 |
-
# Log each result
|
| 104 |
-
writer.writerow({
|
| 105 |
-
'Query': sample_query,
|
| 106 |
-
'Result Number': i + 1,
|
| 107 |
-
'Page Number': res['page_num'],
|
| 108 |
-
'Content': res['content']
|
| 109 |
-
})
|
| 110 |
-
|
| 111 |
-
print(f"Results for query '{sample_query}' logged to {log_file}\n")
|
| 112 |
-
except Exception as e:
|
| 113 |
-
print(f"Error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|