Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,525 +1,552 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import os
|
| 3 |
-
import tempfile
|
| 4 |
-
import google.generativeai as genai
|
| 5 |
-
from pypdf import PdfReader
|
| 6 |
-
from pinecone import Pinecone
|
| 7 |
-
import uuid
|
| 8 |
-
import time
|
| 9 |
-
import json
|
| 10 |
-
from dotenv import load_dotenv
|
| 11 |
-
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 12 |
-
|
| 13 |
-
# Load environment variables from .env file
|
| 14 |
-
load_dotenv()
|
| 15 |
-
|
| 16 |
-
# Configuration
|
| 17 |
-
st.set_page_config(page_title="PDF Learning Assistant", layout="wide")
|
| 18 |
-
|
| 19 |
-
# Initialize session state
|
| 20 |
-
if "messages" not in st.session_state:
|
| 21 |
-
st.session_state.messages = []
|
| 22 |
-
if "current_pdf_content" not in st.session_state:
|
| 23 |
-
st.session_state.current_pdf_content = ""
|
| 24 |
-
if "current_pdf_name" not in st.session_state:
|
| 25 |
-
st.session_state.current_pdf_name = ""
|
| 26 |
-
if "index_name" not in st.session_state:
|
| 27 |
-
st.session_state.index_name = "index1" # Using your specific index name
|
| 28 |
-
if "is_initialized" not in st.session_state:
|
| 29 |
-
st.session_state.is_initialized = False
|
| 30 |
-
if "index_dimensions" not in st.session_state:
|
| 31 |
-
st.session_state.index_dimensions = 1024 # Set this based on your Pinecone index
|
| 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 |
-
def
|
| 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 |
-
return
|
| 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 |
-
json_start = response.find("```") +
|
| 228 |
-
json_end = response.find("```", json_start)
|
| 229 |
-
json_str = response[json_start:json_end].strip()
|
| 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 |
-
json_start = response.find("```") +
|
| 269 |
-
json_end = response.find("```", json_start)
|
| 270 |
-
json_str = response[json_start:json_end].strip()
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
#
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
st.
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
if st.button("Generate
|
| 367 |
-
with st.spinner("Generating
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
)
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
#
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
import google.generativeai as genai
|
| 5 |
+
from pypdf import PdfReader
|
| 6 |
+
from pinecone import Pinecone
|
| 7 |
+
import uuid
|
| 8 |
+
import time
|
| 9 |
+
import json
|
| 10 |
+
from dotenv import load_dotenv
|
| 11 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 12 |
+
|
| 13 |
+
# Load environment variables from .env file
|
| 14 |
+
load_dotenv()
|
| 15 |
+
|
| 16 |
+
# Configuration
|
| 17 |
+
st.set_page_config(page_title="PDF Learning Assistant", layout="wide")
|
| 18 |
+
|
| 19 |
+
# Initialize session state
|
| 20 |
+
if "messages" not in st.session_state:
|
| 21 |
+
st.session_state.messages = []
|
| 22 |
+
if "current_pdf_content" not in st.session_state:
|
| 23 |
+
st.session_state.current_pdf_content = ""
|
| 24 |
+
if "current_pdf_name" not in st.session_state:
|
| 25 |
+
st.session_state.current_pdf_name = ""
|
| 26 |
+
if "index_name" not in st.session_state:
|
| 27 |
+
st.session_state.index_name = "index1" # Using your specific index name
|
| 28 |
+
if "is_initialized" not in st.session_state:
|
| 29 |
+
st.session_state.is_initialized = False
|
| 30 |
+
if "index_dimensions" not in st.session_state:
|
| 31 |
+
st.session_state.index_dimensions = 1024 # Set this based on your Pinecone index
|
| 32 |
+
if "quiz_submitted" not in st.session_state:
|
| 33 |
+
st.session_state.quiz_submitted = False
|
| 34 |
+
if "quiz_answers" not in st.session_state:
|
| 35 |
+
st.session_state.quiz_answers = {}
|
| 36 |
+
|
| 37 |
+
# Functions for PDF processing
|
| 38 |
+
def extract_text_from_pdf(pdf_file):
|
| 39 |
+
reader = PdfReader(pdf_file)
|
| 40 |
+
text = ""
|
| 41 |
+
for page in reader.pages:
|
| 42 |
+
text += page.extract_text() + "\n"
|
| 43 |
+
return text
|
| 44 |
+
|
| 45 |
+
def chunk_text(text, chunk_size=1000, overlap=200):
|
| 46 |
+
chunks = []
|
| 47 |
+
start = 0
|
| 48 |
+
text_length = len(text)
|
| 49 |
+
|
| 50 |
+
while start < text_length:
|
| 51 |
+
end = min(start + chunk_size, text_length)
|
| 52 |
+
if end < text_length and end - start == chunk_size:
|
| 53 |
+
# Find the last period or newline to make more natural chunks
|
| 54 |
+
last_period = text.rfind('.', start, end)
|
| 55 |
+
last_newline = text.rfind('\n', start, end)
|
| 56 |
+
if last_period > start + chunk_size // 2:
|
| 57 |
+
end = last_period + 1
|
| 58 |
+
elif last_newline > start + chunk_size // 2:
|
| 59 |
+
end = last_newline + 1
|
| 60 |
+
|
| 61 |
+
chunks.append(text[start:end])
|
| 62 |
+
start = end - overlap if end < text_length else text_length
|
| 63 |
+
|
| 64 |
+
return chunks
|
| 65 |
+
|
| 66 |
+
# Embeddings and Vector Store functions
|
| 67 |
+
@st.cache_resource
|
| 68 |
+
def get_embedding_model():
|
| 69 |
+
# Using a model that produces 1024-dimensional embeddings
|
| 70 |
+
return HuggingFaceEmbeddings(model_name="sentence-transformers/all-roberta-large-v1")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def initialize_pinecone():
|
| 74 |
+
# Get API key from environment variables
|
| 75 |
+
api_key = os.getenv("PINECONE_API_KEY")
|
| 76 |
+
|
| 77 |
+
if not api_key:
|
| 78 |
+
st.error("Pinecone API key not found. Please add it to your .env file as PINECONE_API_KEY=your_api_key")
|
| 79 |
+
return False
|
| 80 |
+
|
| 81 |
+
try:
|
| 82 |
+
# Initialize Pinecone with your specific configuration
|
| 83 |
+
pc = Pinecone(api_key=api_key)
|
| 84 |
+
|
| 85 |
+
# Store Pinecone client in session state
|
| 86 |
+
st.session_state.pinecone_client = pc
|
| 87 |
+
|
| 88 |
+
# Check if your index exists
|
| 89 |
+
index_list = [idx.name for idx in pc.list_indexes()]
|
| 90 |
+
if st.session_state.index_name not in index_list:
|
| 91 |
+
st.error(f"Index '{st.session_state.index_name}' not found in your Pinecone account.")
|
| 92 |
+
st.info("Available indexes: " + ", ".join(index_list))
|
| 93 |
+
return False
|
| 94 |
+
|
| 95 |
+
# Get index details to check dimensions
|
| 96 |
+
try:
|
| 97 |
+
index = pc.Index(st.session_state.index_name)
|
| 98 |
+
index_stats = index.describe_index_stats()
|
| 99 |
+
if 'dimension' in index_stats:
|
| 100 |
+
st.session_state.index_dimensions = index_stats['dimension']
|
| 101 |
+
st.info(f"Detected index dimension: {st.session_state.index_dimensions}")
|
| 102 |
+
else:
|
| 103 |
+
st.warning("Could not detect index dimensions. Using default: 1024")
|
| 104 |
+
except Exception as e:
|
| 105 |
+
st.warning(f"Could not get index details: {str(e)}")
|
| 106 |
+
|
| 107 |
+
return True
|
| 108 |
+
except Exception as e:
|
| 109 |
+
st.error(f"Error initializing Pinecone: {str(e)}")
|
| 110 |
+
return False
|
| 111 |
+
|
| 112 |
+
def get_pinecone_index():
|
| 113 |
+
# Connect to your existing index
|
| 114 |
+
return st.session_state.pinecone_client.Index(st.session_state.index_name)
|
| 115 |
+
|
| 116 |
+
def embed_chunks(chunks):
|
| 117 |
+
model = get_embedding_model()
|
| 118 |
+
embeddings = []
|
| 119 |
+
for chunk in chunks:
|
| 120 |
+
# HuggingFaceEmbeddings returns a list with a single embedding
|
| 121 |
+
embed = model.embed_documents([chunk])[0]
|
| 122 |
+
embeddings.append(embed)
|
| 123 |
+
return embeddings
|
| 124 |
+
|
| 125 |
+
def store_embeddings(chunks, embeddings, pdf_name):
|
| 126 |
+
index = get_pinecone_index()
|
| 127 |
+
batch_size = 100
|
| 128 |
+
|
| 129 |
+
for i in range(0, len(chunks), batch_size):
|
| 130 |
+
i_end = min(i + batch_size, len(chunks))
|
| 131 |
+
ids = [f"{pdf_name}-{uuid.uuid4()}" for _ in range(i, i_end)]
|
| 132 |
+
metadata = [{"text": chunks[j], "pdf_name": pdf_name, "chunk_id": j} for j in range(i, i_end)]
|
| 133 |
+
vectors = [(ids[j-i], embeddings[j], metadata[j-i]) for j in range(i, i_end)]
|
| 134 |
+
|
| 135 |
+
try:
|
| 136 |
+
index.upsert(vectors=vectors)
|
| 137 |
+
st.success(f"Successfully stored batch {i//batch_size + 1} of chunks to Pinecone")
|
| 138 |
+
except Exception as e:
|
| 139 |
+
st.error(f"Error storing embeddings: {str(e)}")
|
| 140 |
+
# Display the first embedding's dimension for debugging
|
| 141 |
+
if embeddings and len(embeddings) > 0:
|
| 142 |
+
st.info(f"Embedding dimension: {len(embeddings[0])}")
|
| 143 |
+
return False
|
| 144 |
+
|
| 145 |
+
st.success(f"Successfully stored all {len(chunks)} chunks to Pinecone")
|
| 146 |
+
return True
|
| 147 |
+
|
| 148 |
+
def search_similar_chunks(query, top_k=5, pdf_name=None):
|
| 149 |
+
model = get_embedding_model()
|
| 150 |
+
query_embedding = model.embed_query(query)
|
| 151 |
+
index = get_pinecone_index()
|
| 152 |
+
|
| 153 |
+
filter_query = {"pdf_name": pdf_name} if pdf_name else None
|
| 154 |
+
|
| 155 |
+
results = index.query(
|
| 156 |
+
vector=query_embedding,
|
| 157 |
+
top_k=top_k,
|
| 158 |
+
include_metadata=True,
|
| 159 |
+
filter=filter_query
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
return results.matches
|
| 163 |
+
|
| 164 |
+
# Gemini LLM Integration
|
| 165 |
+
@st.cache_resource
|
| 166 |
+
def initialize_gemini():
|
| 167 |
+
api_key = os.getenv("GOOGLE_API_KEY")
|
| 168 |
+
|
| 169 |
+
if not api_key:
|
| 170 |
+
st.error("Google API key not found. Please add it to your .env file as GOOGLE_API_KEY=your_api_key")
|
| 171 |
+
return False
|
| 172 |
+
|
| 173 |
+
try:
|
| 174 |
+
genai.configure(api_key=api_key)
|
| 175 |
+
return True
|
| 176 |
+
except Exception as e:
|
| 177 |
+
st.error(f"Error initializing Google Generative AI: {str(e)}")
|
| 178 |
+
return False
|
| 179 |
+
|
| 180 |
+
def get_gemini_response(prompt, context=None, temperature=0.7):
|
| 181 |
+
try:
|
| 182 |
+
model = genai.GenerativeModel('gemini-2.0-flash')
|
| 183 |
+
|
| 184 |
+
if context:
|
| 185 |
+
full_prompt = f"""
|
| 186 |
+
Context information:
|
| 187 |
+
{context}
|
| 188 |
+
|
| 189 |
+
Question: {prompt}
|
| 190 |
+
|
| 191 |
+
Please provide a helpful, accurate response based on the context information provided.
|
| 192 |
+
If the answer cannot be determined from the context, please state that clearly.
|
| 193 |
+
"""
|
| 194 |
+
else:
|
| 195 |
+
full_prompt = prompt
|
| 196 |
+
|
| 197 |
+
response = model.generate_content(full_prompt, generation_config={"temperature": temperature})
|
| 198 |
+
return response.text
|
| 199 |
+
except Exception as e:
|
| 200 |
+
st.error(f"Error getting response from Gemini: {str(e)}")
|
| 201 |
+
return "Sorry, I couldn't generate a response at this time."
|
| 202 |
+
|
| 203 |
+
# Quiz and Assignment Generation
|
| 204 |
+
def generate_quiz(pdf_content, num_questions=5):
|
| 205 |
+
prompt = f"""
|
| 206 |
+
Based on the following content, generate a quiz with {num_questions} multiple-choice questions.
|
| 207 |
+
For each question, provide 4 options and indicate the correct answer.
|
| 208 |
+
Format the response as a JSON array of question objects with the structure:
|
| 209 |
+
[
|
| 210 |
+
{{
|
| 211 |
+
"question": "Question text",
|
| 212 |
+
"options": ["Option A", "Option B", "Option C", "Option D"],
|
| 213 |
+
"correct_answer": "Correct option (A, B, C, or D)",
|
| 214 |
+
"explanation": "Brief explanation of why this is the correct answer"
|
| 215 |
+
}},
|
| 216 |
+
// more questions...
|
| 217 |
+
]
|
| 218 |
+
|
| 219 |
+
Content: {pdf_content[:2000]}... (truncated for brevity)
|
| 220 |
+
"""
|
| 221 |
+
|
| 222 |
+
response = get_gemini_response(prompt, temperature=0.2)
|
| 223 |
+
|
| 224 |
+
try:
|
| 225 |
+
# Extract JSON from response if it's embedded in markdown or text
|
| 226 |
+
if "```json" in response:
|
| 227 |
+
json_start = response.find("```json") + 7
|
| 228 |
+
json_end = response.find("```", json_start)
|
| 229 |
+
json_str = response[json_start:json_end].strip()
|
| 230 |
+
elif "```" in response:
|
| 231 |
+
json_start = response.find("```") + 3
|
| 232 |
+
json_end = response.find("```", json_start)
|
| 233 |
+
json_str = response[json_start:json_end].strip()
|
| 234 |
+
else:
|
| 235 |
+
json_str = response
|
| 236 |
+
|
| 237 |
+
quiz_data = json.loads(json_str)
|
| 238 |
+
return quiz_data
|
| 239 |
+
except Exception as e:
|
| 240 |
+
st.error(f"Error parsing quiz response: {str(e)}")
|
| 241 |
+
return []
|
| 242 |
+
|
| 243 |
+
def generate_assignment(pdf_content, assignment_type="short_answer", num_questions=3):
|
| 244 |
+
prompt = f"""
|
| 245 |
+
Based on the following content, generate a {assignment_type} assignment with {num_questions} questions.
|
| 246 |
+
If the assignment type is 'short_answer', create questions that require brief explanations.
|
| 247 |
+
If the assignment type is 'essay', create deeper questions that require longer responses.
|
| 248 |
+
If the assignment type is 'research', create questions that encourage further exploration of the topics.
|
| 249 |
+
|
| 250 |
+
Format the response as a JSON array with the structure:
|
| 251 |
+
[
|
| 252 |
+
{{
|
| 253 |
+
"question": "Question text",
|
| 254 |
+
"hints": ["Hint 1", "Hint 2"],
|
| 255 |
+
"key_points": ["Key point 1", "Key point 2", "Key point 3"]
|
| 256 |
+
}},
|
| 257 |
+
// more questions...
|
| 258 |
+
]
|
| 259 |
+
|
| 260 |
+
Content: {pdf_content[:2000]}... (truncated for brevity)
|
| 261 |
+
"""
|
| 262 |
+
|
| 263 |
+
response = get_gemini_response(prompt, temperature=0.3)
|
| 264 |
+
|
| 265 |
+
try:
|
| 266 |
+
# Extract JSON from response if it's embedded in markdown or text
|
| 267 |
+
if "```json" in response:
|
| 268 |
+
json_start = response.find("```json") + 7
|
| 269 |
+
json_end = response.find("```", json_start)
|
| 270 |
+
json_str = response[json_start:json_end].strip()
|
| 271 |
+
elif "```" in response:
|
| 272 |
+
json_start = response.find("```") + 3
|
| 273 |
+
json_end = response.find("```", json_start)
|
| 274 |
+
json_str = response[json_start:json_end].strip()
|
| 275 |
+
else:
|
| 276 |
+
json_str = response
|
| 277 |
+
|
| 278 |
+
assignment_data = json.loads(json_str)
|
| 279 |
+
return assignment_data
|
| 280 |
+
except Exception as e:
|
| 281 |
+
st.error(f"Error parsing assignment response: {str(e)}")
|
| 282 |
+
return []
|
| 283 |
+
|
| 284 |
+
# Callback functions for quiz submission and reset
|
| 285 |
+
def submit_quiz():
|
| 286 |
+
st.session_state.quiz_submitted = True
|
| 287 |
+
|
| 288 |
+
def reset_quiz():
|
| 289 |
+
st.session_state.quiz_submitted = False
|
| 290 |
+
st.session_state.quiz_answers = {}
|
| 291 |
+
|
| 292 |
+
# Streamlit UI
|
| 293 |
+
def main():
|
| 294 |
+
st.title("📚 PDF Learning Assistant")
|
| 295 |
+
|
| 296 |
+
# Initialize services
|
| 297 |
+
if not st.session_state.is_initialized:
|
| 298 |
+
with st.spinner("Initializing services..."):
|
| 299 |
+
pinecone_init = initialize_pinecone()
|
| 300 |
+
gemini_init = initialize_gemini()
|
| 301 |
+
|
| 302 |
+
if pinecone_init and gemini_init:
|
| 303 |
+
st.session_state.is_initialized = True
|
| 304 |
+
st.success("Services initialized successfully!")
|
| 305 |
+
|
| 306 |
+
# Display Pinecone connection info
|
| 307 |
+
st.info(f"""
|
| 308 |
+
Connected to Pinecone index:
|
| 309 |
+
- Index name: {st.session_state.index_name}
|
| 310 |
+
- Dimension: {st.session_state.index_dimensions}
|
| 311 |
+
- Host: https://index1-mwog0w0.svc.aped-4627-b74a.pinecone.io
|
| 312 |
+
- Region: us-east-1
|
| 313 |
+
- Type: Dense
|
| 314 |
+
- Capacity: Serverless
|
| 315 |
+
""")
|
| 316 |
+
else:
|
| 317 |
+
st.error("Failed to initialize all required services. Please check your API keys in the .env file.")
|
| 318 |
+
|
| 319 |
+
# Show .env file template
|
| 320 |
+
st.code("""
|
| 321 |
+
# Create a .env file in the same directory with the following content:
|
| 322 |
+
PINECONE_API_KEY=your_pinecone_api_key
|
| 323 |
+
GOOGLE_API_KEY=your_google_api_key
|
| 324 |
+
""")
|
| 325 |
+
return
|
| 326 |
+
|
| 327 |
+
# Sidebar for PDF upload and main actions
|
| 328 |
+
with st.sidebar:
|
| 329 |
+
st.header("Upload PDF")
|
| 330 |
+
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
|
| 331 |
+
|
| 332 |
+
if uploaded_file:
|
| 333 |
+
with st.spinner("Processing PDF..."):
|
| 334 |
+
# Save uploaded file to temp location
|
| 335 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
|
| 336 |
+
temp_file.write(uploaded_file.getvalue())
|
| 337 |
+
temp_path = temp_file.name
|
| 338 |
+
|
| 339 |
+
# Extract text
|
| 340 |
+
pdf_text = extract_text_from_pdf(temp_path)
|
| 341 |
+
os.unlink(temp_path) # Delete temp file
|
| 342 |
+
|
| 343 |
+
# Store in session state
|
| 344 |
+
st.session_state.current_pdf_content = pdf_text
|
| 345 |
+
st.session_state.current_pdf_name = uploaded_file.name
|
| 346 |
+
|
| 347 |
+
# Chunk and embed
|
| 348 |
+
chunks = chunk_text(pdf_text)
|
| 349 |
+
embeddings = embed_chunks(chunks)
|
| 350 |
+
|
| 351 |
+
# Store in Pinecone
|
| 352 |
+
success = store_embeddings(chunks, embeddings, st.session_state.current_pdf_name)
|
| 353 |
+
|
| 354 |
+
if success:
|
| 355 |
+
st.success(f"Successfully processed {uploaded_file.name}")
|
| 356 |
+
else:
|
| 357 |
+
st.error(f"Failed to process {uploaded_file.name}")
|
| 358 |
+
|
| 359 |
+
st.divider()
|
| 360 |
+
st.header("Learning Tools")
|
| 361 |
+
|
| 362 |
+
# Only enable these buttons if a PDF is loaded
|
| 363 |
+
if st.session_state.current_pdf_content:
|
| 364 |
+
# Quiz generation
|
| 365 |
+
quiz_questions = st.slider("Number of quiz questions", min_value=3, max_value=10, value=5)
|
| 366 |
+
if st.button("Generate Quiz"):
|
| 367 |
+
with st.spinner("Generating quiz..."):
|
| 368 |
+
quiz_data = generate_quiz(st.session_state.current_pdf_content, num_questions=quiz_questions)
|
| 369 |
+
st.session_state.quiz_data = quiz_data
|
| 370 |
+
# Reset quiz state when generating a new quiz
|
| 371 |
+
reset_quiz()
|
| 372 |
+
|
| 373 |
+
# Assignment generation
|
| 374 |
+
assignment_type = st.selectbox(
|
| 375 |
+
"Assignment Type",
|
| 376 |
+
["short_answer", "essay", "research"]
|
| 377 |
+
)
|
| 378 |
+
assignment_questions = st.slider("Number of assignment questions", min_value=1, max_value=5, value=3)
|
| 379 |
+
|
| 380 |
+
if st.button("Generate Assignment"):
|
| 381 |
+
with st.spinner("Generating assignment..."):
|
| 382 |
+
assignment_data = generate_assignment(
|
| 383 |
+
st.session_state.current_pdf_content,
|
| 384 |
+
assignment_type,
|
| 385 |
+
num_questions=assignment_questions
|
| 386 |
+
)
|
| 387 |
+
st.session_state.assignment_data = assignment_data
|
| 388 |
+
else:
|
| 389 |
+
st.info("Please upload a PDF first to use these features")
|
| 390 |
+
|
| 391 |
+
# Main content area
|
| 392 |
+
tab1, tab2, tab3 = st.tabs(["Chatbot", "Quiz", "Assignment"])
|
| 393 |
+
|
| 394 |
+
# Tab 1: Chatbot
|
| 395 |
+
with tab1:
|
| 396 |
+
st.header("Chat with your PDF")
|
| 397 |
+
|
| 398 |
+
# Display chat messages
|
| 399 |
+
for message in st.session_state.messages:
|
| 400 |
+
with st.chat_message(message["role"]):
|
| 401 |
+
st.write(message["content"])
|
| 402 |
+
|
| 403 |
+
# Chat input
|
| 404 |
+
if st.session_state.current_pdf_content:
|
| 405 |
+
user_input = st.chat_input("Ask a question about your PDF...")
|
| 406 |
+
|
| 407 |
+
if user_input:
|
| 408 |
+
# Add user message to chat history
|
| 409 |
+
st.session_state.messages.append({"role": "user", "content": user_input})
|
| 410 |
+
with st.chat_message("user"):
|
| 411 |
+
st.write(user_input)
|
| 412 |
+
|
| 413 |
+
# Generate response
|
| 414 |
+
with st.chat_message("assistant"):
|
| 415 |
+
with st.spinner("Thinking..."):
|
| 416 |
+
# Search for relevant context
|
| 417 |
+
similar_chunks = search_similar_chunks(
|
| 418 |
+
user_input,
|
| 419 |
+
top_k=3,
|
| 420 |
+
pdf_name=st.session_state.current_pdf_name
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
# Extract text from results
|
| 424 |
+
context = "\n\n".join([match.metadata["text"] for match in similar_chunks])
|
| 425 |
+
|
| 426 |
+
# Get response from Gemini
|
| 427 |
+
response = get_gemini_response(user_input, context)
|
| 428 |
+
|
| 429 |
+
st.write(response)
|
| 430 |
+
|
| 431 |
+
# Add assistant message to chat history
|
| 432 |
+
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 433 |
+
else:
|
| 434 |
+
st.info("Please upload a PDF to start chatting")
|
| 435 |
+
|
| 436 |
+
# Tab 2: Quiz
|
| 437 |
+
with tab2:
|
| 438 |
+
st.header("Quiz")
|
| 439 |
+
|
| 440 |
+
if "quiz_data" in st.session_state and st.session_state.quiz_data:
|
| 441 |
+
quiz_data = st.session_state.quiz_data
|
| 442 |
+
|
| 443 |
+
# Quiz display logic - static until submitted
|
| 444 |
+
if not st.session_state.quiz_submitted:
|
| 445 |
+
# Quiz form
|
| 446 |
+
with st.form(key="quiz_form"):
|
| 447 |
+
for i, question in enumerate(quiz_data):
|
| 448 |
+
st.subheader(f"Question {i+1}")
|
| 449 |
+
st.write(question["question"])
|
| 450 |
+
|
| 451 |
+
options = question["options"]
|
| 452 |
+
option_labels = ["A", "B", "C", "D"]
|
| 453 |
+
|
| 454 |
+
# Create radio buttons for options
|
| 455 |
+
answer = st.radio(
|
| 456 |
+
"Select your answer:",
|
| 457 |
+
options=option_labels[:len(options)],
|
| 458 |
+
key=f"q{i}",
|
| 459 |
+
index=None
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
# Display options
|
| 463 |
+
for j, option in enumerate(options):
|
| 464 |
+
st.write(f"{option_labels[j]}: {option}")
|
| 465 |
+
|
| 466 |
+
# Store answer in session state
|
| 467 |
+
if answer:
|
| 468 |
+
st.session_state.quiz_answers[i] = answer
|
| 469 |
+
|
| 470 |
+
st.divider()
|
| 471 |
+
|
| 472 |
+
# Submit button inside the form
|
| 473 |
+
submit_button = st.form_submit_button("Submit Quiz")
|
| 474 |
+
if submit_button:
|
| 475 |
+
st.session_state.quiz_submitted = True
|
| 476 |
+
else:
|
| 477 |
+
# Show results after submission
|
| 478 |
+
correct_count = 0
|
| 479 |
+
|
| 480 |
+
for i, question in enumerate(quiz_data):
|
| 481 |
+
st.subheader(f"Question {i+1}")
|
| 482 |
+
st.write(question["question"])
|
| 483 |
+
|
| 484 |
+
options = question["options"]
|
| 485 |
+
option_labels = ["A", "B", "C", "D"]
|
| 486 |
+
correct_letter = question["correct_answer"]
|
| 487 |
+
user_answer = st.session_state.quiz_answers.get(i)
|
| 488 |
+
|
| 489 |
+
# Display options with correct/incorrect indicators
|
| 490 |
+
for j, option in enumerate(options):
|
| 491 |
+
current_label = option_labels[j]
|
| 492 |
+
if current_label == correct_letter:
|
| 493 |
+
st.success(f"{current_label}: {option} ✓")
|
| 494 |
+
if user_answer == current_label:
|
| 495 |
+
correct_count += 1
|
| 496 |
+
elif user_answer == current_label:
|
| 497 |
+
st.error(f"{current_label}: {option} ✗")
|
| 498 |
+
else:
|
| 499 |
+
st.write(f"{current_label}: {option}")
|
| 500 |
+
|
| 501 |
+
# Show explanation
|
| 502 |
+
st.info(f"Explanation: {question['explanation']}")
|
| 503 |
+
st.divider()
|
| 504 |
+
|
| 505 |
+
st.subheader(f"Your Score: {correct_count}/{len(quiz_data)}")
|
| 506 |
+
|
| 507 |
+
if st.button("Retake Quiz"):
|
| 508 |
+
reset_quiz()
|
| 509 |
+
else:
|
| 510 |
+
st.info("Generate a quiz from the sidebar to see it here")
|
| 511 |
+
|
| 512 |
+
# Tab 3: Assignment
|
| 513 |
+
# Tab 3: Assignment
|
| 514 |
+
with tab3:
|
| 515 |
+
st.header("Assignment")
|
| 516 |
+
|
| 517 |
+
if "assignment_data" in st.session_state and st.session_state.assignment_data:
|
| 518 |
+
assignment_data = st.session_state.assignment_data
|
| 519 |
+
|
| 520 |
+
# Create a form for the assignment
|
| 521 |
+
with st.form(key="assignment_form"):
|
| 522 |
+
for i, question in enumerate(assignment_data):
|
| 523 |
+
st.subheader(f"Question {i+1}")
|
| 524 |
+
st.write(question["question"])
|
| 525 |
+
|
| 526 |
+
# Use a checkbox to toggle hints instead of a nested expander
|
| 527 |
+
if "hints" in question and question["hints"]:
|
| 528 |
+
show_hints = st.checkbox(f"Show hints for Question {i+1}", key=f"hint_checkbox_{i}")
|
| 529 |
+
if show_hints:
|
| 530 |
+
for hint in question["hints"]:
|
| 531 |
+
st.write(f"- {hint}")
|
| 532 |
+
|
| 533 |
+
# Input area for the answer
|
| 534 |
+
st.text_area("Your Answer:", key=f"assignment_q{i}", height=150)
|
| 535 |
+
st.divider()
|
| 536 |
+
|
| 537 |
+
# Add the submit button as a direct child of the form
|
| 538 |
+
submit_assignment = st.form_submit_button("Submit Assignment")
|
| 539 |
+
|
| 540 |
+
# Process form submission outside the form block
|
| 541 |
+
if submit_assignment:
|
| 542 |
+
st.success("Assignment submitted! Here are the key points for each question:")
|
| 543 |
+
for i, question in enumerate(assignment_data):
|
| 544 |
+
with st.expander(f"Key Points for Question {i+1}", expanded=True):
|
| 545 |
+
for point in question["key_points"]:
|
| 546 |
+
st.write(f"- {point}")
|
| 547 |
+
else:
|
| 548 |
+
st.info("Generate an assignment from the sidebar to see it here")
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
if __name__ == "__main__":
|
| 552 |
+
main()
|