DEV Community

Akshay Keerthi
Akshay Keerthi

Posted on

Building Grammar Analyzer using Lyzr SDK

Are you tired of spending countless hours perfecting your documents, only to find pesky grammar errors and typos lingering within?

Look no further! We’re thrilled to introduce Grammar Analyzer, a revolutionary tool powered by Lyzr’s cutting-edge SDK, designed to streamline your proofreading process and elevate your writing to new heights.

Image description

Grammar Analyzer simplifies the daunting task of proofreading by leveraging the advanced capabilities of Lyzr’s QABot. With just a few clicks, you can upload your document and let Grammar Analyzer do the heavy lifting. Gone are the days of manual line-by-line scrutiny; our intelligent bot swiftly identifies grammar, spelling, and punctuation errors, allowing you to focus on crafting flawless prose.

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 streamlit as st
import shutil
from lyzr import QABot
Enter fullscreen mode Exit fullscreen mode

The provided code imports necessary Python libraries for file manipulation (os and shutil) and web application development (streamlit). Additionally, it imports the QABot class from the lyzr module, indicating involvement with language processing tasks. The lyzr module presumably offers functionalities related to text analysis or natural language understanding.

Next Set Up OpenAI API Key and using Streamlit’s secrets management, set up the OpenAI API key within your Streamlit application. Replace "OPENAI_API_KEY" with the actual key name defined in your Streamlit secrets where your OpenAI API key is stored.

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

This function, remove_existing_files(directory), is designed to delete all existing files and directories within a specified directory. It iterates through each item in the specified directory using os.listdir(directory). For each item, it constructs the full file path by joining the directory path with the item's filename. Then, it attempts to remove the item using os.unlink() if it's a file or shutil.rmtree() if it's a directory. If any errors occur during the removal process, it catches them and displays an error message 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"])

if uploaded_file 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 the path of the stored file
    st.success(f"File successfully saved")
Enter fullscreen mode Exit fullscreen mode

This code snippet creates a file upload widget using Streamlit, allowing users to select Word files (“docx” format). Upon file selection, it saves the uploaded Word file to a local directory named “data”. The code then displays a success message confirming the file’s successful saving.

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 QA bot
    path = get_files_in_directory()
    path = path[0]

    rag = QABot.docx_qa(
        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

This function, rag_implementation(), implements the RAG Lyzr QA bot. It begins by retrieving the file path from the get_files_in_directory() function, then selects the first file path from the list. Subsequently, it initializes an instance of the QABot class, specifically designed for document question answering. It configures the bot with the selected file path and specifies the model to use. Finally, it returns the configured QA bot instance.

def resume_response():
    rag = rag_implementation()
    prompt = """  Follow the intructions as given below ,
                    - Run spell check to identify misspelled words. Correct each flagged word, ensuring accurate spelling and context.
                    - Carefully review for grammar and sentence structure errors. Correct subject-verb agreement, tense misuse, and punctuation errors.
                    - Proofread line by line, focusing on syntax, coherence, and clarity. Rectify awkward phrasing, unclear language, and inconsistencies in writing style. Rewrite or rephrase sentences for enhanced readability.
                    - Keep the corrected document and print it. Start printing the corrected version from the next line after this statement: "Correct version:".
                    - Errors : Show the errors in the document and it has been changed."""


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

This resume_response() function orchestrates the response generation process using the RAG Lyzr QA bot. It first initializes the RAG QA bot using the **rag_implementation() **function. Then, it defines a prompt containing instructions for reviewing and correcting a document for spelling, grammar, and coherence. Next, it queries the RAG bot with the prompt, prompting it to generate a response. Finally, it returns the response generated by the bot.

At Lyzr, we’re committed to empowering writers of all skill levels to express themselves with confidence. Whether you’re drafting a business proposal, crafting a creative masterpiece, or polishing your resume, Grammar Analyzer equips you with the tools you need to shine.

Ready to elevate your writing? Experience the power of Grammar Analyzer today!

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

App link: https://grammar-analyzer-lyzr.streamlit.app/

Source Code: https://github.com/isakshay007/Grammer-Checker

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)