Revolutionize Studying with Lyzr's Assessment Generator: A Comprehensive Guide
Published: 2024-03-22 11:51:38

Studying from extensive textbook materials can often be daunting for students, especially when it comes to summarizing content and extracting key insights. However, [Lyzr ](https://www.lyzr.ai/) presents the "Assessment Generator" application, a solution designed to streamline the studying process by generating insightful questions based on uploaded textbook PDFs. 

In this article, we'll delve into the features and functionalities of the Assessment Generator, providing you with a comprehensive guide to building this GenAI application with [Lyzr's QABot agent](https://docs.lyzr.ai/lyzr-sdk/opensource/qa-bot/).

---

{% embed https://docs.lyzr.ai/homepage %}

---
Lyzr provides an agentic way to build LLM applications in no time and low code, even if you are not familiar with the GenAI stack, and want to build your AI application so Lyzr is your go solution to build the GenAI apps without having a deep understanding of Generative AI.

## Setting up the Project
**Clone the Assessment Generator repository**

Link - [GitHub](https://github.com/PrajjwalLyzr/Assessment-Generator)

**Set up a virtual environment**

```bash
python3 -m venv venv
source venv/bin/activate

```
Create an environment file named **.env** and add your OpenAI API key and Weaviate cluster URL and API key

```bash
OPENAI_API_KEY = "Your_OpenAI_API_Key"
VECTOR_STORE_URL = "Your_Weaviate_Cluster_URL"
VECTOR_STORE_API = "Your_Weaviate_Cluster_API"

```
**Install the required dependencies**

```bash
pip install lyzr streamlit pdfminer.six

```

## Project Structure

The project structure of the Assessment Generator looks like this:

```scss
Assessment-Generator
│
├── utils/
│   ├── __init__.py
│   └── utils.py
│
├── app.py
│
├── README.md
│
├── .env
│
├── .gitignore
│
└── requirements.txt

```

## Quick Look of Assessment Generator

{% embed https://youtu.be/v-Xb9B8A1GE?si=QI41gJNIz18txV-s %}

## Start with utils.py

The utils directory contains utility functions used throughout the application, utils.py file contains utility functions that are essential for the functioning of the Assessment Generator application. 

**remove_existing_files**: This function removes all existing files and directories within a specified directory, ensuring a clean workspace for processing new uploads.

```python
import os
import shutil
import streamlit as st
from pathlib import Path
import pandas as pd

def remove_existing_files(directory):
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as e:
            st.error(f"Error while removing existing files: {e}")
```

**get_files_in_directory**: This function retrieves a list of file paths within a specified directory, which is useful for obtaining files for further processing or analysis.

```python
def get_files_in_directory(directory):
    # This function help us to get the file path along with filename.
    files_list = []

    if os.path.exists(directory) and os.path.isdir(directory):
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)
            
            if os.path.isfile(file_path):
                files_list.append(file_path)

    return files_list
```
**save_uploaded_file**: Responsible for saving an uploaded file to the 'data' directory, this function ensures that the uploaded PDF is stored securely for processing.

```python
def save_uploaded_file(uploaded_file):
    # Function to save uploaded file
    remove_existing_files('data')

    file_path = os.path.join('data', uploaded_file.name)
    with open(file_path, "wb") as file:
        file.write(uploaded_file.read())
    st.success("File uploaded successfully")

    rev = uploaded_file.name[::-1]
    rev = rev[4:]
    filename = rev[::-1]
    
    return filename[:3]
```

**user_subject_topics**: This function generates important study questions based on the specified subject and topics within the textbook, leveraging Lyzr's QABot agent.

```python
def user_subject_topics(agent, subject, topics_lst):
        resposne_flash = {}
        for topic in topics_lst:
            prompt = f"""You are an expert of this {subject}, Can you write down 3-5 important questions on this {subject} and its topics: {topic} """
            response = agent.query(prompt)
            if response is not None:
                if response.response == 'Empty Response':
                    st.warning('Please provide valid pdf')

                elif response.response != 'Empty Response':    
                    resposne_flash[topic] = response.response.split('?')
        
        return resposne_flash
```

**flashcard_viewer**: Displays the generated study questions in a user-friendly format, allowing students to easily review and study the material.

```python
def flashcard_viewer(response:dict):
    for topic, questions in response.items():
        st.subheader(topic)
        for question in questions:
            st.write(question)
        st.markdown("---") 
```
 

## Initiating the Application

In the app.py file, the application is initiated using Streamlit. Users are prompted to upload a PDF file, specify the subject and topics, and click the "Generate" button to generate study questions.

```python
import os
from PIL import Image
from utils import utils
import streamlit as st
from dotenv import load_dotenv; load_dotenv()
from lyzr import QABot

# create directory if it doesn't exist
data = "data"
os.makedirs(data, exist_ok=True)

 

def vector_store_configuration(bookname):
    vector_store_params = {
    "vector_store_type": "WeaviateVectorStore",
    "url": os.getenv('VECTOR_STORE_URL'), 
    "api_key": os.getenv('VECTOR_STORE_API'), 
    "index_name": f"Book{bookname}IndexName" 
  }
    
    return vector_store_params

```
The function vector_store_configuration returns a dictionary containing parameters for configuring a vector store. These parameters include the type of vector store, its URL, API key, and an index name based on the provided book name. 

## Assessment Generator with QABot Agent

 It utilizes Lyzr’s QABot Agent, and this agent uses RAG to perform analysis on the provided PDF file.

```python
def smartstudy_bot(filepath, vector_params):
    "This function will implement the Lyzr's QA agent to summarize the Youtube Video"
    smartstudy = QABot.pdf_qa(
            input_files=[str(filepath)],
            vector_store_params=vector_params
        )
    
    return smartstudy
```
The input_files parameter is set to a list containing the path to the PDF file, and the vector_store_params parameter is provided to configure the vector store. The function returns the initialized smartstudy object, which can be used to interact with the QA agent for further analysis.

```python
if __name__ == "__main__":
    uploaded_file = st.file_uploader("Choose PDF file", type=["pdf"])
    if uploaded_file is not None:
        filename = utils.save_uploaded_file(uploaded_file)
        subject_name = st.text_input("Write the subject of your Book")
        topics = st.text_input("Enter topics (by comma seperated)")
        topics_list = [topic.strip() for topic in topics.split(",") if topic.strip()]

        if topics_list is not None:
            if st.button("Generate"):
                path = utils.get_files_in_directory(data)
                filepath = path[0]
                vector_params = vector_store_configuration(filename)
                study_agent = smartstudy_bot(filepath=filepath, vector_params=vector_params)
                if study_agent is not None:
                    topic_response = utils.user_subject_topics(agent=study_agent, subject=subject_name, topics_lst=topics_list)
                    utils.flashcard_viewer(response=topic_response)
```
The study agent is then used to generate questions related to the provided subject and topics using the utils.user_subject_topics function and questions are displayed using the utils.flashcard_viewer function.

## Conclusion

With Lyzr's Assessment Generator, students can revolutionize their studying experience by effortlessly generating personalized study questions tailored to their textbook materials. By leveraging the power of AI, this application simplifies the process of summarizing content and extracting key insights, empowering students to study more efficiently and effectively.

## References

For further exploration and engagement, refer to Lyzr’s website, book a demo, or join the community channels on Discord and Slack.

**Assessment Generator**: [GitHub](https://github.com/PrajjwalLyzr/Assessment-Generator)

**Lyzr Website**: [https://www.lyzr.ai/](https://www.lyzr.ai/)

**Book a Demo**: [https://www.lyzr.ai/book-demo/](https://www.lyzr.ai/book-demo/)

**Lyzr Community Channels**: [Discord](https://discord.com/invite/nm7zSyEFA2), [Slack](https://anybodycanai.slack.com/join/shared_invite/zt-2a7fr38f7-_QDOY1W1WSlSiYNAEncLGw#/shared-invite/email)