DEV Community

Cover image for Struggling with Inventory Management? This Might Help!
harshit-lyzr
harshit-lyzr

Posted on

Struggling with Inventory Management? This Might Help!

Are you struggling to manage your inventory efficiently? Do you wish there was a smarter way to analyze your inventory data and derive actionable insights from it? Look no further! In this blog post, we'll explore how to build an Inventory Manager using Lyzr and Streamlit, two powerful tools that can revolutionize the way you handle your inventory.

Managing inventory can be a daunting task, especially as your business grows. It involves keeping track of stock levels, forecasting demand, and making informed decisions to optimize inventory turnover. Traditional methods of inventory management often rely on manual processes and basic spreadsheet tools, which can be time-consuming and prone to errors.

With the advancements in technology, we now have access to sophisticated data analytics tools that can streamline the inventory management process. Lyzr is one such tool that leverages artificial intelligence to analyze data and provide valuable insights. Combined with Streamlit, a popular framework for building interactive web applications, we can create a user-friendly Inventory Manager that simplifies the task of inventory management.

Setting Up the Environment
app.py file
Imports:

__import__('pysqlite3')
import sys
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')

import os
from lyzr import DataAnalyzr
from dotenv import load_dotenv
import streamlit as st
from utils import save_uploaded_file
from PIL import Image
Enter fullscreen mode Exit fullscreen mode

import pysqlite3: Imports the pysqlite3 module, but it's swapped with sqlite3 later, likely for compatibility reasons.
import sys: Provides system-specific functions.
import os: Provides functions for interacting with the operating system (OS).
from lyzr import DataAnalyzr: Imports the DataAnalyzr class from the lyzr library, likely used for data analysis tasks.
from dotenv import load_dotenv: Imports the load_dotenv function from the dotenv library, used to load environment variables from a .env file.
import streamlit as st: Imports the streamlit library for creating web apps.
from utils import save_uploaded_file: Imports the save_uploaded_file function from the utils module, presumably for handling file uploads.
from PIL import Image: Imports the Image class from the Pillow (PIL Fork) library for image processing.

Environment Variable Loading:

load_dotenv()
api = os.getenv('OPENAI_API_KEY')
Enter fullscreen mode Exit fullscreen mode

load_dotenv(): Loads environment variables from a .env file (likely containing an API key).

Data Directory Creation:

data = "data"
os.makedirs(data, exist_ok=True)
Enter fullscreen mode Exit fullscreen mode

data = "data": Defines a variable data to store the path to the data directory.
os.makedirs(data, exist_ok=True): Creates the data directory if it doesn't exist, ignoring errors if it already exists.

data_uploader Function:

def data_uploader():
    st.subheader("Upload Data file")
    # Upload csv file
    uploaded_file = st.file_uploader("Choose csv file", type=["csv"])
    if uploaded_file is not None:
        save_uploaded_file(uploaded_file)
Creates a subheader using st.subheader.
Provides a file upload option for CSV files using st.file_uploader.
Calls the save_uploaded_file function (from utils) to save the uploaded file, presumably in the data directory.

file_checker Function:
def file_checker():
    file = []
    for filename in os.listdir(data):
        file_path = os.path.join(data, filename)
        file.append(file_path)

    return file
Enter fullscreen mode Exit fullscreen mode

Creates an empty list file to store file paths.
Iterates through files in the data directory using os.listdir.
Constructs the full file path for each file.
Appends the file path to the file list.
Returns the list of file paths.

inventory_manager Function:

def inventory_manager(path, question):
    analyzr = DataAnalyzr(analysis_type="sql", api_key=api)
    datafiles = {
        "test1": path,

    }
    # Call the get_data method
    analyzr.get_data(
        db_type = "files",
        config = {
                "datasets": datafiles,
        },
        vector_store_config = {}
    )

    result = analyzr.ask(
        user_input = f"you are an inventory manager.Your Task is to Give Answer for Question from given Dataset: {question}",
        outputs=["insights","recommendations","tasks"]
    )

    return result
Enter fullscreen mode Exit fullscreen mode

Creates a DataAnalyzr object from the lyzr library, specifying analysis type ("sql") and API key.
Defines a dictionary datafiles to map a dataset name ("test1") to the uploaded file path.
Calls the DataAnalyzr.get_data method to retrieve data from the file(s).
Constructs the user query by prompting the user to be an inventory manager answering questions from a dataset.
Calls the DataAnalyzr.ask method with the user query, requesting insights, recommendations, and tasks.
Returns the analysis results (insights, recommendations, tasks).

Main Block:

if __name__ == "__main__":
    style_app()
    st.sidebar.markdown("## Welcome to the Lyzr Inventory Manager!")
    selection = st.sidebar.radio("Go to", ["Data", "Analysis"])

    if selection == "Data":
        data_uploader()
    elif selection == "Analysis":
        file = file_checker()
        if len(file) > 0:
            questions = st.text_input("Enter Your Question: ")
            if st.button("Generate"):
                answer = inventory_manager(file[0], questions)
                st.markdown("## Insights")
                st.markdown(answer['insights'])
                st.markdown("## Recommendations: ")
                st.markdown(answer['recommendations'])
                st.markdown("## Tasks:")
                st.markdown(answer['tasks'])
Enter fullscreen mode Exit fullscreen mode

Provides a radio button selection in the sidebar using st.sidebar.radio ("Data" or "Analysis").

Conditional Logic:
If "Data" is selected:
Calls the data_uploader function to display the file upload section.
If "Analysis" is selected:
Calls the file_checker function to get a list of uploaded files.
If there are uploaded files:
Prompts the user for a question using st.text_input.
If a "Generate" button is clicked:
Calls the inventory_manager function with the first uploaded file path and the user's question.
Displays the analysis results (insights, recommendations, tasks) using st.markdown.

utils.py

import os
import shutil
import streamlit as st

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}")

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

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")
Enter fullscreen mode Exit fullscreen mode

Above code cleans data directory, retrieves file list, and saves uploaded files.

try it now: https://inventorymanager-6srplcbrgzf3ae59rqvprt.streamlit.app/
Github: https://github.com/harshit-lyzr/inventory_manager
For more information explore the website: Lyzr

Top comments (0)