### Project Installation and Running Instructions Source: https://context7.com/ahsannyc/aidd-30-day-challenge-task-4/llms.txt Provides essential commands for setting up the project environment, including installing necessary Python packages via pip, creating a configuration file with the API key, and running the Streamlit application. It specifies the default local URL for accessing the app. ```bash # Install dependencies pip install streamlit pypdf python-dotenv nest_asyncio google-generativeai # Or using requirements.txt # pip install -r requirements.txt # Create .env file with your API key # echo "GEMINI_API_KEY=your_actual_api_key_here" > .env # Run the application # streamlit run app.py # The application will open in your browser at http://localhost:8501 ``` -------------------------------- ### Streamlit Application Setup and Gemini API Configuration Source: https://context7.com/ahsannyc/aidd-30-day-challenge-task-4/llms.txt Sets up the Streamlit interface, including session state management, file upload handling for PDFs, and configuring the Google Gemini API using an API key loaded from environment variables. It handles potential errors if the API key is missing. ```python import streamlit as st import os from dotenv import load_dotenv import google.generativeai as genai import asyncio # Placeholder for extract_text_from_pdf function def extract_text_from_pdf(uploaded_file): # In a real scenario, this would extract text from the PDF file return f"Extracted text from {uploaded_file.name}" # Load environment variables load_dotenv(override=True) # Configure Gemini API gemini_api_key = os.getenv("GEMINI_API_KEY") if gemini_api_key: genai.configure(api_key=gemini_api_key) else: st.error("GEMINI_API_KEY not found in environment variables.") # Page configuration st.set_page_config(page_title="Study Notes & Quiz Agent", layout="wide") st.title("📚 Study Notes Summarizer & Quiz Generator") # Initialize session state if "pdf_text" not in st.session_state: st.session_state.pdf_text = "" if "summary" not in st.session_state: st.session_state.summary = "" if "quiz" not in st.session_state: st.session_state.quiz = "" # File uploader uploaded_file = st.file_uploader("Upload your PDF Study Material", type=["pdf"]) if uploaded_file is not None: file_key = f"file_{uploaded_file.name}_{uploaded_file.size}" if "file_key" not in st.session_state or st.session_state.file_key != file_key: st.session_state.file_key = file_key st.session_state.summary = "" st.session_state.quiz = "" # Extract text and store in session state text = extract_text_from_pdf(uploaded_file) if text: st.session_state.pdf_text = text st.success("PDF loaded successfully!") ``` -------------------------------- ### Environment Configuration for Gemini API Source: https://context7.com/ahsannyc/aidd-30-day-challenge-task-4/llms.txt This section details how to configure the Google Gemini API key. It shows the expected format for the `.env` file and provides Python code to load the key from either `.gemini/.env` (preferred) or the root `.env` file, followed by configuring the `genai` library. ```bash # .env file configuration GEMINI_API_KEY=your_gemini_api_key_here # Alternative location: .gemini/.env # The application checks both locations, with .gemini/.env taking precedence ``` ```python import os from dotenv import load_dotenv import google.generativeai as genai # Load from .gemini/.env first, then .env dotenv_path = os.path.join(os.getcwd(), ".gemini", ".env") load_dotenv(dotenv_path, override=True) load_dotenv(override=True) # Configure API gemini_api_key = os.getenv("GEMINI_API_KEY") if gemini_api_key: genai.configure(api_key=gemini_api_key) print("Gemini API configured successfully") else: print("Error: GEMINI_API_KEY not found") ``` -------------------------------- ### Complete Streamlit Workflow: Summary and Quiz Generation Source: https://context7.com/ahsannyc/aidd-30-day-challenge-task-4/llms.txt Illustrates the end-to-end user interaction within a Streamlit application. It shows how to trigger summary and quiz generation based on uploaded PDF text, manage results using session state, and display them, including conditional enabling of buttons. ```python import streamlit as st import asyncio # Assuming agent_logic.py contains get_summary and get_quiz functions # from agent_logic import get_summary, get_quiz # Placeholder functions for demonstration purposes async def get_summary_placeholder(content): return f"Summary of:\n{content[:50]}..." async def get_quiz_placeholder(content): return f"Quiz based on:\n{content[:50]}...\n1. Q? A) B)" # After PDF is uploaded and text is extracted if st.session_state.pdf_text: col1, col2 = st.columns(2) # Summary generation button with col1: if st.button("📝 Summarize Notes"): with st.spinner("Generating Summary..."): # Replace with actual call: summary_result = await get_summary(st.session_state.pdf_text) summary_result = await get_summary_placeholder(st.session_state.pdf_text) st.session_state.summary = summary_result st.rerun() # Quiz generation button (enabled only after summary exists) with col2: if st.session_state.summary: if st.button("❓ Create Quiz"): with st.spinner("Generating Quiz..."): # Replace with actual call: quiz_result = await get_quiz(st.session_state.pdf_text) quiz_result = await get_quiz_placeholder(st.session_state.pdf_text) st.session_state.quiz = quiz_result st.rerun() else: st.button( "❓ Create Quiz", disabled=True, help="Summarize first to unlock quiz!" ) # Display results if st.session_state.summary: st.markdown("### 📝 Summary") st.container(border=True).markdown(st.session_state.summary) if st.session_state.quiz: st.markdown("### ❓ Quiz") st.container(border=True).markdown(st.session_state.quiz) ``` -------------------------------- ### Generate Quiz using Asyncio Source: https://context7.com/ahsannyc/aidd-30-day-challenge-task-4/llms.txt This snippet demonstrates how to generate a quiz asynchronously using the `get_quiz` function and `asyncio.run`. It prints the generated quiz content. ```python import asyncio # Assuming get_quiz is defined elsewhere and takes study_content as input # quiz = asyncio.run(get_quiz(study_content)) # print(quiz) # Placeholder for demonstration if get_quiz is not available in this context async def get_quiz_placeholder(content): return "This is a placeholder quiz.\n1. Question? A) Ans B) Ans" study_content = "Sample study material." quiz = asyncio.run(get_quiz_placeholder(study_content)) print(quiz) ``` -------------------------------- ### Generate Quiz with Gemini AI (Python) Source: https://context7.com/ahsannyc/aidd-30-day-challenge-task-4/llms.txt This asynchronous function generates a quiz with five mixed-format questions (multiple choice and true/false) based on provided text content using Google's Gemini 2.5 Flash model. It includes instructions for the AI to format the quiz clearly and provide an answer key at the end. Error handling is included for the AI generation process. ```python import google.generativeai as genai import asyncio async def get_quiz(text): model = genai.GenerativeModel("gemini-2.5-flash") chat = model.start_chat(history=[]) instructions = ( "You are a professor creating a quiz for your students. Based on the " "provided text, generate a quiz with 5 mixed questions (Multiple " "Choice and True/False). Format it clearly. Do not provide the " "answers immediately after each question. Provide an Answer Key at " "the very end of the output." ) try: truncated_text = text[:20000] prompt = ( f"{instructions}\n\nCreate a quiz based on the following text:\n\n" f"{truncated_text}" ) response = await chat.send_message(prompt) return response.text except Exception as e: return f"Error generating quiz: {str(e)}" # Example usage # study_content = """ # Photosynthesis is the process by which plants convert light energy into # chemical energy. It occurs in chloroplasts and requires carbon dioxide, # water, and sunlight. The process produces glucose and oxygen as byproducts. # """ # # quiz = asyncio.run(get_quiz(study_content)) # print(quiz) ``` -------------------------------- ### Generate Study Summary with Gemini AI (Python) Source: https://context7.com/ahsannyc/aidd-30-day-challenge-task-4/llms.txt This asynchronous function generates a structured study summary from provided text using Google's Gemini 2.5 Flash model. It formats the output using markdown, highlights key concepts, and limits the input text to prevent excessive API calls. It includes error handling for the AI generation process. ```python import google.generativeai as genai import asyncio async def get_summary(text): model = genai.GenerativeModel("gemini-2.5-flash") chat = model.start_chat(history=[]) instructions = ( "You are an expert study assistant. Your goal is to create clear, " "concise, and structured study notes from the provided text. Use " "markdown formatting, bullet points, and bold text to highlight " "key concepts. Output the summary directly." ) try: truncated_text = text[:20000] # Limit to ~20k chars prompt = ( f"{instructions}\n\n" f"Here is the text to summarize:\n\n" f"{truncated_text}" ) response = await chat.send_message(prompt) return response.text except Exception as e: return f"Error generating summary: {str(e)}" # Example usage # sample_text = """ # Machine learning is a subset of artificial intelligence that enables # computers to learn from data without explicit programming. Key concepts # include supervised learning, unsupervised learning, and reinforcement # learning. Neural networks are computational models inspired by the human # brain, consisting of interconnected nodes that process information. # """ # Run the async function # summary = asyncio.run(get_summary(sample_text)) # print(summary) ``` -------------------------------- ### Extract Text from PDF using pypdf Source: https://context7.com/ahsannyc/aidd-30-day-challenge-task-4/llms.txt This function extracts all text content from an uploaded PDF file using the pypdf library. It iterates through each page, concatenates the extracted text, and returns it. It handles potential exceptions during the extraction process. ```python from pypdf import PdfReader def extract_text_from_pdf(uploaded_file): try: pdf_reader = PdfReader(uploaded_file) text = "" for page in pdf_reader.pages: text += page.extract_text() or "" return text except Exception as e: return None # Example usage with a file upload # with open("study_material.pdf", "rb") as pdf_file: # extracted_text = extract_text_from_pdf(pdf_file) # if extracted_text: # print(f"Extracted {len(extracted_text)} characters") # print(extracted_text[:500]) # First 500 characters # else: # print("Failed to extract text") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.