DEV Community

Akshay Keerthi
Akshay Keerthi

Posted on

Building Poem Generator using Lyzr SDK

Are you looking for a tool to spark your creativity and help you craft captivating poems effortlessly? Look no further! With Lyzr’s intuitive Poem Generator integrated into a user-friendly Streamlit application, you can now refine your writing skills and unleash your imagination like never before.

Image description

Poetry has always been a powerful medium for expressing emotions, thoughts, and stories. However, for many, the process of crafting a poem can be daunting. From brainstorming ideas to structuring verses and refining language, it requires both creativity and skill. That’s where Lyzr’s Poem Generator comes in.

Introducing Lyzr’s Poem Generator

Built using Lyzr’s Software Development Kit (SDK), the Poem Generator application harnesses the capabilities of artificial intelligence to assist users in generating high-quality poems effortlessly. Powered by OpenAI’s GPT-3.5 model, this application seamlessly integrates Lyzr’s ChatBot functionality, allowing users to interact with the AI to generate personalized poems based on their input.

Why use Lyzr SDK’s? 
Enter fullscreen mode Exit fullscreen mode

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 code begins by importing necessary modules for file management (such as os and shutil) and for building web applications (like streamlit). Additionally, it imports the ChatBot class from the lyzr module, indicating a possible integration of a chatbot functionality, likely utilizing natural language processing capabilities.

Following this, it initializes the OpenAI API key using Streamlit’s secrets management. By referencing the specific key stored in Streamlit’s secrets, where the OpenAI API key is stored securely, it replaces the placeholder “OPENAI_API_KEY”. This ensures safe 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
# Function to remove existing files 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 manage a local directory named “data” in the file system. Initially, the variable data_directory is assigned the string “data”, representing the name of the directory to be used. Then, the code 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.

Subsequently, remove_existing_files(data_directory) function is called to clear any existing files or subdirectories within the “data” directory, ensuring it is empty and ready for use.

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 checks if a file has been uploaded by the user. If an uploaded file exists, it constructs a file path where the uploaded file will be saved within a specified directory. Then, it opens the file in binary write mode and writes the content of the uploaded file to the specified file path. Finally, it displays a success message to the user, confirming that the file has been successfully saved.

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.

# Function to implement RAG Lyzr Chatbot def rag_implementation(): # Get the file path file_path = get_files_in_directory()[0] # Initialize the RAG Lyzr ChatBot rag = ChatBot.docx_chat( input_files=[file_path], llm_params={"model": "gpt-3.5-turbo"}, ) return rag 
Enter fullscreen mode Exit fullscreen mode

The **rag_implementation()** function manages the integration of the RAG Lyzr Chatbot. Initially, it retrieves the file path by utilizing the **get_files_in_directory()** function, which gathers a list of files within the directory. Then, it selects the first file from the obtained list. Subsequently, it instantiates an instance of the RAG Chatbot, denoted as rag, employing the **ChatBot.docx_chat()** method. This method necessitates the file path containing the conversation history and additional parameters specifying the language model, such as GPT-3.5 Turbo in this instance. Ultimately, the function returns the initialized chatbot instance rag.

def resume_response(): file_path = get_files_in_directory()[0] rag = rag_implementation() prompt = f"""To generate user stories and use cases for your project/product based on the uploaded document, please follow the instructions below: - Product Vision and Goals: Identify and describe the overarching vision and goals of the product. What specific problem is the product aiming to solve? - Target Audience and User Personas: Identify the primary users of the product and describe their demographics, behaviors, and needs to create user personas. - Functional Requirements: Identify and specify the functionalities and features the product should have, highlighting both primary features and any additional capabilities required. - Non-functional Requirements: Identify and specify non-functional requirements such as performance, scalability, security, and usability. - User Flows and Workflows: Identify and illustrate typical user flows and workflows within the product. - Acceptance Criteria: Identify and clarify the conditions that must be met for a user story to be considered complete and accepted by stakeholders. - Constraints and Limitations: Identify any constraints or limitations that may impact feature development and implementation. - Use Cases: Based on above information give multiple use cases that can used for by the user. - User Stories: Based on the provided information, craft multiple user stories that represent specific user needs and actions within the product. - Ensure that the information provided for Product Vision and Goals, Target Audience and User Personas, Functional Requirements, Non-Functional Requirements, User Flows and Workflows, Acceptance Criteria, and Constraints and Limitations is precise and comprehensive not more than 3 bullet points. - The generated Use Cases and User Stories should be clearly explained individually with relevance to the product's context and objectives.""" response = rag.chat(prompt) return response.response if uploaded_file is not None: automatice_response = resume_response() st.markdown(f"""{automatice_response}""") 
Enter fullscreen mode Exit fullscreen mode

The provided code defines a function resume_response() which generates user stories and use cases based on the content of an uploaded document. It first retrieves the path of a file from a directory (presumably containing relevant project/product information), then initializes a RAG ChatBot instance.

The function constructs a prompt with specific instructions for generating user stories and use cases, covering various aspects such as product vision, target audience, requirements, user flows, acceptance criteria, and more. It then uses the RAG ChatBot to process the prompt and generate a response, which is returned.

When an uploaded file exists (uploaded_file is not None), the code calls resume_response() to generate the response, and the generated response is displayed using Streamlit's st.markdown() function. This ensures that the user can receive automatically generated user stories and use cases based on the uploaded document, streamlining the process of project/product planning and development.

The Poem Generator isn’t just a tool — it’s a gateway to new possibilities. Whether you’re a seasoned poet seeking inspiration or a novice writer exploring the world of verse, Lyzr’s Poem Generator invites you to embark on a poetic journey like never before.

So why wait? Embrace your creativity, refine your writing, and unlock the power of poetry with Lyzr’s Poem Generator.

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

App link: https://poem-generator-lyzr.streamlit.app/

Source Code: https://github.com/isakshay007/Poem_Generator

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)