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ec2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5443d3f
c125ec2
 
 
 
5443d3f
c125ec2
 
 
 
 
 
5443d3f
 
 
 
c125ec2
 
5443d3f
c125ec2
5443d3f
 
 
 
c125ec2
5443d3f
c125ec2
5443d3f
 
 
 
 
 
 
 
 
 
c125ec2
 
 
 
5443d3f
c125ec2
 
5443d3f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
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
358
359
360
361
362
363
364
365
366
367
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
import streamlit as st
import os
import tempfile
import google.generativeai as genai
from pypdf import PdfReader
from pinecone import Pinecone
import uuid
import time
import json
from dotenv import load_dotenv
from langchain_community.embeddings import HuggingFaceEmbeddings

# Load environment variables from .env file
load_dotenv()

# Configuration
st.set_page_config(page_title="PDF Learning Assistant", layout="wide")

# Initialize session state
if "messages" not in st.session_state:
    st.session_state.messages = []
if "current_pdf_content" not in st.session_state:
    st.session_state.current_pdf_content = ""
if "current_pdf_name" not in st.session_state:
    st.session_state.current_pdf_name = ""
if "index_name" not in st.session_state:
    st.session_state.index_name = "index1"  # Using your specific index name
if "is_initialized" not in st.session_state:
    st.session_state.is_initialized = False
if "index_dimensions" not in st.session_state:
    st.session_state.index_dimensions = 1024  # Set this based on your Pinecone index
if "quiz_submitted" not in st.session_state:
    st.session_state.quiz_submitted = False
if "quiz_answers" not in st.session_state:
    st.session_state.quiz_answers = {}

# Functions for PDF processing
def extract_text_from_pdf(pdf_file):
    reader = PdfReader(pdf_file)
    text = ""
    for page in reader.pages:
        text += page.extract_text() + "\n"
    return text

def chunk_text(text, chunk_size=1000, overlap=200):
    chunks = []
    start = 0
    text_length = len(text)
    
    while start < text_length:
        end = min(start + chunk_size, text_length)
        if end < text_length and end - start == chunk_size:
            # Find the last period or newline to make more natural chunks
            last_period = text.rfind('.', start, end)
            last_newline = text.rfind('\n', start, end)
            if last_period > start + chunk_size // 2:
                end = last_period + 1
            elif last_newline > start + chunk_size // 2:
                end = last_newline + 1
        
        chunks.append(text[start:end])
        start = end - overlap if end < text_length else text_length
    
    return chunks

# Embeddings and Vector Store functions
@st.cache_resource
def get_embedding_model():
    # Using a model that produces 1024-dimensional embeddings
    return HuggingFaceEmbeddings(model_name="sentence-transformers/all-roberta-large-v1")


def initialize_pinecone():
    # Get API key from environment variables
    api_key = os.getenv("PINECONE_API_KEY")
    
    if not api_key:
        st.error("Pinecone API key not found. Please add it to your .env file as PINECONE_API_KEY=your_api_key")
        return False
    
    try:
        # Initialize Pinecone with your specific configuration
        pc = Pinecone(api_key=api_key)
        
        # Store Pinecone client in session state
        st.session_state.pinecone_client = pc
        
        # Check if your index exists
        index_list = [idx.name for idx in pc.list_indexes()]
        if st.session_state.index_name not in index_list:
            st.error(f"Index '{st.session_state.index_name}' not found in your Pinecone account.")
            st.info("Available indexes: " + ", ".join(index_list))
            return False
        
        # Get index details to check dimensions
        try:
            index = pc.Index(st.session_state.index_name)
            index_stats = index.describe_index_stats()
            if 'dimension' in index_stats:
                st.session_state.index_dimensions = index_stats['dimension']
                st.info(f"Detected index dimension: {st.session_state.index_dimensions}")
            else:
                st.warning("Could not detect index dimensions. Using default: 1024")
        except Exception as e:
            st.warning(f"Could not get index details: {str(e)}")
        
        return True
    except Exception as e:
        st.error(f"Error initializing Pinecone: {str(e)}")
        return False

def get_pinecone_index():
    # Connect to your existing index
    return st.session_state.pinecone_client.Index(st.session_state.index_name)

def embed_chunks(chunks):
    model = get_embedding_model()
    embeddings = []
    for chunk in chunks:
        # HuggingFaceEmbeddings returns a list with a single embedding
        embed = model.embed_documents([chunk])[0]
        embeddings.append(embed)
    return embeddings

def store_embeddings(chunks, embeddings, pdf_name):
    index = get_pinecone_index()
    batch_size = 100
    
    for i in range(0, len(chunks), batch_size):
        i_end = min(i + batch_size, len(chunks))
        ids = [f"{pdf_name}-{uuid.uuid4()}" for _ in range(i, i_end)]
        metadata = [{"text": chunks[j], "pdf_name": pdf_name, "chunk_id": j} for j in range(i, i_end)]
        vectors = [(ids[j-i], embeddings[j], metadata[j-i]) for j in range(i, i_end)]
        
        try:
            index.upsert(vectors=vectors)
            st.success(f"Successfully stored batch {i//batch_size + 1} of chunks to Pinecone")
        except Exception as e:
            st.error(f"Error storing embeddings: {str(e)}")
            # Display the first embedding's dimension for debugging
            if embeddings and len(embeddings) > 0:
                st.info(f"Embedding dimension: {len(embeddings[0])}")
            return False
    
    st.success(f"Successfully stored all {len(chunks)} chunks to Pinecone")
    return True

def search_similar_chunks(query, top_k=5, pdf_name=None):
    model = get_embedding_model()
    query_embedding = model.embed_query(query)
    index = get_pinecone_index()
    
    filter_query = {"pdf_name": pdf_name} if pdf_name else None
    
    results = index.query(
        vector=query_embedding,
        top_k=top_k,
        include_metadata=True,
        filter=filter_query
    )
    
    return results.matches

# Gemini LLM Integration
@st.cache_resource
def initialize_gemini():
    api_key = os.getenv("GOOGLE_API_KEY")
    
    if not api_key:
        st.error("Google API key not found. Please add it to your .env file as GOOGLE_API_KEY=your_api_key")
        return False
    
    try:
        genai.configure(api_key=api_key)
        return True
    except Exception as e:
        st.error(f"Error initializing Google Generative AI: {str(e)}")
        return False

def get_gemini_response(prompt, context=None, temperature=0.7):
    try:
        model = genai.GenerativeModel('gemini-2.0-flash')
        
        if context:
            full_prompt = f"""
            Context information: 
            {context}
            
            Question: {prompt}
            
            Please provide a helpful, accurate response based on the context information provided. 
            If the answer cannot be determined from the context, please state that clearly.
            """
        else:
            full_prompt = prompt
            
        response = model.generate_content(full_prompt, generation_config={"temperature": temperature})
        return response.text
    except Exception as e:
        st.error(f"Error getting response from Gemini: {str(e)}")
        return "Sorry, I couldn't generate a response at this time."

# Quiz and Assignment Generation
def generate_quiz(pdf_content, num_questions=5):
    prompt = f"""
    Based on the following content, generate a quiz with {num_questions} multiple-choice questions. 
    For each question, provide 4 options and indicate the correct answer.
    Format the response as a JSON array of question objects with the structure:
    [
        {{
            "question": "Question text", 
            "options": ["Option A", "Option B", "Option C", "Option D"],
            "correct_answer": "Correct option (A, B, C, or D)",
            "explanation": "Brief explanation of why this is the correct answer"
        }},
        // more questions...
    ]
    
    Content: {pdf_content[:2000]}... (truncated for brevity)
    """
    
    response = get_gemini_response(prompt, temperature=0.2)
    
    try:
        # Extract JSON from response if it's embedded in markdown or text
        if "```json" in response:
            json_start = response.find("```json") + 7
            json_end = response.find("```", json_start)
            json_str = response[json_start:json_end].strip()
        elif "```" in response:
            json_start = response.find("```") + 3
            json_end = response.find("```", json_start)
            json_str = response[json_start:json_end].strip()
        else:
            json_str = response
            
        quiz_data = json.loads(json_str)
        return quiz_data
    except Exception as e:
        st.error(f"Error parsing quiz response: {str(e)}")
        return []

def generate_assignment(pdf_content, assignment_type="short_answer", num_questions=3):
    prompt = f"""
    Based on the following content, generate a {assignment_type} assignment with {num_questions} questions.
    If the assignment type is 'short_answer', create questions that require brief explanations.
    If the assignment type is 'essay', create deeper questions that require longer responses.
    If the assignment type is 'research', create questions that encourage further exploration of the topics.
    
    Format the response as a JSON array with the structure:
    [
        {{
            "question": "Question text",
            "hints": ["Hint 1", "Hint 2"],
            "key_points": ["Key point 1", "Key point 2", "Key point 3"]
        }},
        // more questions...
    ]
    
    Content: {pdf_content[:2000]}... (truncated for brevity)
    """
    
    response = get_gemini_response(prompt, temperature=0.3)
    
    try:
        # Extract JSON from response if it's embedded in markdown or text
        if "```json" in response:
            json_start = response.find("```json") + 7
            json_end = response.find("```", json_start)
            json_str = response[json_start:json_end].strip()
        elif "```" in response:
            json_start = response.find("```") + 3
            json_end = response.find("```", json_start)
            json_str = response[json_start:json_end].strip()
        else:
            json_str = response
            
        assignment_data = json.loads(json_str)
        return assignment_data
    except Exception as e:
        st.error(f"Error parsing assignment response: {str(e)}")
        return []

# Callback functions for quiz submission and reset
def submit_quiz():
    st.session_state.quiz_submitted = True

def reset_quiz():
    st.session_state.quiz_submitted = False
    st.session_state.quiz_answers = {}

# Streamlit UI
def main():
    st.title("📚 PDF Learning Assistant")
    
    # Initialize services
    if not st.session_state.is_initialized:
        with st.spinner("Initializing services..."):
            pinecone_init = initialize_pinecone()
            gemini_init = initialize_gemini()
            
            if pinecone_init and gemini_init:
                st.session_state.is_initialized = True
                st.success("Services initialized successfully!")
                
                # Display Pinecone connection info
                st.info(f"""
                Connected to Pinecone index:
                - Index name: {st.session_state.index_name}
                - Dimension: {st.session_state.index_dimensions}
                - Host: https://index1-mwog0w0.svc.aped-4627-b74a.pinecone.io
                - Region: us-east-1
                - Type: Dense
                - Capacity: Serverless
                """)
            else:
                st.error("Failed to initialize all required services. Please check your API keys in the .env file.")
                
                # Show .env file template
                st.code("""
# Create a .env file in the same directory with the following content:
PINECONE_API_KEY=your_pinecone_api_key
GOOGLE_API_KEY=your_google_api_key
                """)
                return
    
    # Sidebar for PDF upload and main actions
    with st.sidebar:
        st.header("Upload PDF")
        uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
        
        if uploaded_file:
            with st.spinner("Processing PDF..."):
                # Save uploaded file to temp location
                with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
                    temp_file.write(uploaded_file.getvalue())
                    temp_path = temp_file.name
                
                # Extract text
                pdf_text = extract_text_from_pdf(temp_path)
                os.unlink(temp_path)  # Delete temp file
                
                # Store in session state
                st.session_state.current_pdf_content = pdf_text
                st.session_state.current_pdf_name = uploaded_file.name
                
                # Chunk and embed
                chunks = chunk_text(pdf_text)
                embeddings = embed_chunks(chunks)
                
                # Store in Pinecone
                success = store_embeddings(chunks, embeddings, st.session_state.current_pdf_name)
                
                if success:
                    st.success(f"Successfully processed {uploaded_file.name}")
                else:
                    st.error(f"Failed to process {uploaded_file.name}")
        
        st.divider()
        st.header("Learning Tools")
        
        # Only enable these buttons if a PDF is loaded
        if st.session_state.current_pdf_content:
            # Quiz generation
            quiz_questions = st.slider("Number of quiz questions", min_value=3, max_value=10, value=5)
            if st.button("Generate Quiz"):
                with st.spinner("Generating quiz..."):
                    quiz_data = generate_quiz(st.session_state.current_pdf_content, num_questions=quiz_questions)
                    st.session_state.quiz_data = quiz_data
                    # Reset quiz state when generating a new quiz
                    reset_quiz()
            
            # Assignment generation
            assignment_type = st.selectbox(
                "Assignment Type", 
                ["short_answer", "essay", "research"]
            )
            assignment_questions = st.slider("Number of assignment questions", min_value=1, max_value=5, value=3)
            
            if st.button("Generate Assignment"):
                with st.spinner("Generating assignment..."):
                    assignment_data = generate_assignment(
                        st.session_state.current_pdf_content, 
                        assignment_type,
                        num_questions=assignment_questions
                    )
                    st.session_state.assignment_data = assignment_data
        else:
            st.info("Please upload a PDF first to use these features")
    
    # Main content area
    tab1, tab2, tab3 = st.tabs(["Chatbot", "Quiz", "Assignment"])
    
    # Tab 1: Chatbot
    with tab1:
        st.header("Chat with your PDF")
        
        # Display chat messages
        for message in st.session_state.messages:
            with st.chat_message(message["role"]):
                st.write(message["content"])
        
        # Chat input
        if st.session_state.current_pdf_content:
            user_input = st.chat_input("Ask a question about your PDF...")
            
            if user_input:
                # Add user message to chat history
                st.session_state.messages.append({"role": "user", "content": user_input})
                with st.chat_message("user"):
                    st.write(user_input)
                
                # Generate response
                with st.chat_message("assistant"):
                    with st.spinner("Thinking..."):
                        # Search for relevant context
                        similar_chunks = search_similar_chunks(
                            user_input, 
                            top_k=3, 
                            pdf_name=st.session_state.current_pdf_name
                        )
                        
                        # Extract text from results
                        context = "\n\n".join([match.metadata["text"] for match in similar_chunks])
                        
                        # Get response from Gemini
                        response = get_gemini_response(user_input, context)
                        
                        st.write(response)
                        
                        # Add assistant message to chat history
                        st.session_state.messages.append({"role": "assistant", "content": response})
        else:
            st.info("Please upload a PDF to start chatting")
    
    # Tab 2: Quiz
    with tab2:
        st.header("Quiz")
        
        if "quiz_data" in st.session_state and st.session_state.quiz_data:
            quiz_data = st.session_state.quiz_data
            
            # Quiz display logic - static until submitted
            if not st.session_state.quiz_submitted:
                # Quiz form
                with st.form(key="quiz_form"):
                    for i, question in enumerate(quiz_data):
                        st.subheader(f"Question {i+1}")
                        st.write(question["question"])
                        
                        options = question["options"]
                        option_labels = ["A", "B", "C", "D"]
                        
                        # Create radio buttons for options
                        answer = st.radio(
                            "Select your answer:",
                            options=option_labels[:len(options)],
                            key=f"q{i}",
                            index=None
                        )
                        
                        # Display options
                        for j, option in enumerate(options):
                            st.write(f"{option_labels[j]}: {option}")
                        
                        # Store answer in session state
                        if answer:
                            st.session_state.quiz_answers[i] = answer
                        
                        st.divider()
                    
                    # Submit button inside the form
                    submit_button = st.form_submit_button("Submit Quiz")
                    if submit_button:
                        st.session_state.quiz_submitted = True
            else:
                # Show results after submission
                correct_count = 0
                
                for i, question in enumerate(quiz_data):
                    st.subheader(f"Question {i+1}")
                    st.write(question["question"])
                    
                    options = question["options"]
                    option_labels = ["A", "B", "C", "D"]
                    correct_letter = question["correct_answer"]
                    user_answer = st.session_state.quiz_answers.get(i)
                    
                    # Display options with correct/incorrect indicators
                    for j, option in enumerate(options):
                        current_label = option_labels[j]
                        if current_label == correct_letter:
                            st.success(f"{current_label}: {option} ✓")
                            if user_answer == current_label:
                                correct_count += 1
                        elif user_answer == current_label:
                            st.error(f"{current_label}: {option} ✗")
                        else:
                            st.write(f"{current_label}: {option}")
                    
                    # Show explanation
                    st.info(f"Explanation: {question['explanation']}")
                    st.divider()
                
                st.subheader(f"Your Score: {correct_count}/{len(quiz_data)}")
                
                if st.button("Retake Quiz"):
                    reset_quiz()
        else:
            st.info("Generate a quiz from the sidebar to see it here")
    
    # Tab 3: Assignment
# Tab 3: Assignment
    with tab3:
        st.header("Assignment")
        
        if "assignment_data" in st.session_state and st.session_state.assignment_data:
            assignment_data = st.session_state.assignment_data
            
            # Create a form for the assignment
            with st.form(key="assignment_form"):
                for i, question in enumerate(assignment_data):
                    st.subheader(f"Question {i+1}")
                    st.write(question["question"])
                    
                    # Use a checkbox to toggle hints instead of a nested expander
                    if "hints" in question and question["hints"]:
                        show_hints = st.checkbox(f"Show hints for Question {i+1}", key=f"hint_checkbox_{i}")
                        if show_hints:
                            for hint in question["hints"]:
                                st.write(f"- {hint}")
                    
                    # Input area for the answer
                    st.text_area("Your Answer:", key=f"assignment_q{i}", height=150)
                    st.divider()
                
                # Add the submit button as a direct child of the form
                submit_assignment = st.form_submit_button("Submit Assignment")
            
            # Process form submission outside the form block
            if submit_assignment:
                st.success("Assignment submitted! Here are the key points for each question:")
                for i, question in enumerate(assignment_data):
                    with st.expander(f"Key Points for Question {i+1}", expanded=True):
                        for point in question["key_points"]:
                            st.write(f"- {point}")
        else:
            st.info("Generate an assignment from the sidebar to see it here")
    

if __name__ == "__main__":
    main()