DEV Community

Akshay Keerthi
Akshay Keerthi

Posted on

Building a Study Planner using Lyzr SDK

Are you tired of feeling overwhelmed by your studies? Do you find it challenging to stay organized and on track with your learning goals? Look no further — the Study Planner app is here to revolutionize the way you approach studying.

Image description

Introducing the Study Planner App

The Study Planner app is a powerful tool designed to help students like you create personalized study schedules that optimize learning efficiency and retention. Powered by advanced AI technology from Lyzr, our app takes the guesswork out of planning your study sessions, allowing you to focus on what matters most — mastering your coursework.

Why use Lyzr SDK’s?

With Lyzr SDKs, crafting your own GenAI application is a breeze, requiring only a few lines of code to get up and running swiftly.

Checkout the Lyzr SDK’s

Lets get Started!
Create a new file app.py and use that

import os
import shutil
import streamlit as st
from lyzr import ChatBot
Enter fullscreen mode Exit fullscreen mode

The script begins by importing necessary modules for file management (os, shutil) and web application development (streamlit). Additionally, it imports the ChatBot class from the lyzr module, indicating potential integration with a chatbot feature, likely utilizing natural language processing capabilities.

Following this, it sets up the OpenAI API key by using Streamlit’s secrets management. The actual key name defined in Streamlit secrets, where the OpenAI API key is stored, replaces “OPENAI_API_KEY”. This ensures secure access to the OpenAI API within the Streamlit application.

# Set the OpenAI API key
os.environ["OPENAI_API_KEY"] = st.secrets["apikey"]
Enter fullscreen mode Exit fullscreen mode
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}")
Enter fullscreen mode Exit fullscreen mode

The function remove_existing_files(directory) serves to erase all files and directories within a designated directory. It traverses through each item within the specified directory using os.listdir(directory). For every item encountered, it forms the complete file path by combining the directory path with the item's filename. Subsequently, it tries to eliminate the item utilizing os.unlink() for files or shutil.rmtree() for directories. In case of any errors during this removal procedure, it handles them and presents an error notification using Streamlit's st.error() function.

# Set the local directory
data_directory = "data"

# Create the data directory if it doesn't exist
os.makedirs(data_directory, exist_ok=True)

# Remove existing files in the data directory
remove_existing_files(data_directory)
Enter fullscreen mode Exit fullscreen mode

These lines of code are responsible for managing a local directory named “data” within the file system. Initially, it sets the variable data_directory to the string "data", representing the name of the directory to be used. Next, it creates the "data" directory using os.makedirs(data_directory, exist_ok=True). The exist_ok=True parameter ensures that the directory is created only if it doesn't already exist. Following this, it calls the remove_existing_files(data_directory) function to clear out any existing files or subdirectories within the "data" directory, ensuring it's empty and ready for use.

# File upload widget
uploaded_file = st.file_uploader("Choose Word file", type=["docx"])

# User inputs for number of free days in a week and number of months for preparation
if uploaded_file is not None:
    num_free_days_week = st.number_input("Number of free days in a week", min_value=1, max_value=7, value=3)
    num_months_preparation = st.number_input("Number of months for preparation", min_value=1, value=2)
    button_clicked = st.button("OK")
else:
    num_free_days_week = None
    num_months_preparation = None
    button_clicked = False
Enter fullscreen mode Exit fullscreen mode

This section of code sets up a file upload widget using Streamlit, allowing users to select Word files (“docx” format). If a file is uploaded, the code prompts the user to input the number of free days in a week and the number of months for preparation using number input widgets provided by Streamlit. Additionally, it displays an “OK” button using st.button(). If no file is uploaded, the variables num_free_days_week, num_months_preparation, and button_clicked are set to None and False respectively.

def get_files_in_directory(directory="data"):
    # This function helps us get the file path along with the filename.
    files_list = []

    # Ensure the directory exists
    if os.path.exists(directory) and os.path.isdir(directory):
        # Iterate through all files in the directory
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)

            # Check if the path points to a file (not a directory)
            if os.path.isfile(file_path):
                files_list.append(file_path)

    return files_list
Enter fullscreen mode Exit fullscreen mode

This function, get_files_in_directory(directory="data"), retrieves a list of file paths from the specified directory. It checks if the directory exists and is valid, then iterates through its contents. For each file found, it appends the file path to a list. Finally, it returns the list of file paths, excluding directories.

def rag_implementation():
    # This function will implement RAG Lyzr Chatbot
    path = get_files_in_directory()
    path = path[0]

    rag = ChatBot.docx_chat(
        input_files=[str(path)],
        llm_params={"model": "gpt-3.5-turbo"},
        # vector_store_params=vector_store_params
    )

    return rag
Enter fullscreen mode Exit fullscreen mode

The rag_implementation() function handles the implementation of the RAG Lyzr Chatbot. Initially, it retrieves the file path using the get_files_in_directory() function. Next, it selects the first file from the list of files obtained. Subsequently, it initializes an instance of the RAG Chatbot named rag using the ChatBot.docx_chat() method. This method requires the path to the input file containing the conversation history and parameters specifying the language model to be used, such as GPT-3.5 Turbo in this case. Finally, the function returns the initialized chatbot instance rag.

# Function to get Lyzr response
def resume_response():
    rag = rag_implementation()
    prompt = f"""Please follow the instructions below to create a study schedule based on the provided syllabus, the number of free days in a week ({num_free_days_week} days), and the number of months for preparation ({num_months_preparation} months):

- After that, create an effective study plan for the topics provided.
- Ensure that all the topics are covered within the crash study plan.
- Try to specify in-depth about each day and the subjects that can be studied."""

    response = rag.chat(prompt)
    return response.response
Enter fullscreen mode Exit fullscreen mode

The resume_response() function generates a response from the Lyzr Chatbot based on provided instructions for creating a study schedule. It first initializes the chatbot, constructs a prompt containing specific study schedule instructions, and then engages in a conversation with the chatbot using this prompt. Finally, it returns the response generated by the chatbot.

# If file is uploaded and user inputs are provided
if button_clicked:
    if uploaded_file is not None and num_free_days_week is not None and num_months_preparation is not None:
        # Save the uploaded Word file to the data directory
        file_path = os.path.join(data_directory, uploaded_file.name)
        with open(file_path, "wb") as file:
            file.write(uploaded_file.getvalue())

        # Display success message
        st.success(f"File successfully saved")

        # Get Lyzr response
        automatic_response = resume_response()
        st.markdown(f"""{automatic_response}""")
Enter fullscreen mode Exit fullscreen mode

This code block executes if the “OK” button is clicked, indicating that the user has uploaded a file and provided input for the number of free days in a week and the number of months for preparation.

It checks if a file is uploaded (uploaded_file is not None) and if the user inputs are provided (num_free_days_week and num_months_preparation are not None).

If all conditions are met, it saves the uploaded Word file to the data directory, displays a success message confirming the file’s saving, retrieves a response from the Lyzr Chatbot using the resume_response() function, and finally displays the generated response.

Don’t let disorganization and inefficiency hold you back from reaching your academic goals. With the Study Planner app, you can take control of your study routine and achieve success with confidence. Try it today and experience the difference for yourself!

Youtube Link: https://www.youtube.com/watch?v=WPhNNvxpgL4

App link: https://study-planner-lyzr.streamlit.app/

Source Code: https://github.com/isakshay007/Study-Planner

Connect with Lyzr
To learn more about Lyzr and its SDK’s, visit our website or get in touch with our team:

Website: Lyzr.ai
Book a Demo: Book a Demo
Discord: Join our Discord community
Slack: Join our Slack channel

Top comments (0)