In today’s digital age, organizing and categorizing books can be a tedious task, especially when dealing with large collections. Whether you’re a book lover, a librarian, or a content manager, knowing which genre each book belongs to can significantly enhance how you search and display your collection.
In this blog post, we'll explore how GenAI can automate the task of categorizing books into their appropriate genres using a simple Python script and the powerful Ollama API.
In this blog post, we’ll show you how to create a simple program that categorizes a list of books into different genres using an AI model. The model we’ll use, Ollama’s Llama3.2, is perfect for processing natural language tasks like this. All you need is a list of book titles, and the AI will handle the categorization and sorting.
Step 1: Preparing the Book List
Before we dive into the code, let’s assume you have a text file (bookList.txt) that contains a list of book titles.
bookList.txt
The Shadows We Left Behind The Enchanted Kingdom of Everwood Chronicles of the Nebula Whispers in the Dark Through His Eyes: The Life of an Artist Cold Blooded: The Hunt for a Killer Power Struggles: Politics in the 21st Century The Art of Living: A Journey Through Thought The Rise and Fall of Empires Living a Balanced Life: A Guide to Wellness Codebreaker: The Future of AI and Data Security The New Age of Business: Strategies for the Modern Entrepreneur A Canvas for Creativity: Exploring Art’s Boundaries Beyond the Classroom: Reimagining Education for the Future Flavors of the World: A Culinary Adventure Champion’s Spirit: The Stories Behind the Victories Laughter is the Best Medicine: Tales of Everyday Funny Moments The Gentle Guide: Raising Happy and Confident Children Savor: A Gourmet’s Guide to Delicious Feasts Whispers of the Forgotten Forest The Moonlit Voyager In the Footsteps of Giants The Lost City of Mirage Echoes of the Eternal Dawn Beneath the Starry Sky The Silent Witness Crossroads of Destiny The Song of the Sea Guardians of the Ancient Flame The Secret of the Golden Key Tales from the Edge of the World Threads of Fate A Journey Through Shadows The Invisible Thread Whispers in the Wind A Dance with Time The Silent City The Curse of the Red Moon Wings of the Phoenix
This list is just the starting point. The goal is to categorize these books into genres such as Fantasy, Literary, Thriller, and Science Fiction.
Step 2: Python Script to Categorize Books
Let’s break down the Python program that uses the Ollama API to categorize and sort these books.
bookCategorizer.py
import ollama import os # Function to check if the input file exists, if not, it exits the program. def check_input_file(file_path): """ Check if the input file exists at the given path. If not, print an error and exit the program. """ if not os.path.exists(file_path): print(f"Input File '{file_path}' not found") exit(1) # Function to read book list from the file def read_book_list(file_path): """ Reads the book list from the specified file and returns it as a string. """ with open(file_path, "r") as file: return file.read().strip() # Function to create the prompt for the Ollama AI model def create_prompt(book_list): """ Creates the prompt to categorize and sort the books based on the given list. """ return f""" You are an assistant that categorizes and sorts the books Here is the list of books {book_list} Please: 1. Categorize these books into appropriate genres such as Fantasy, Literary, Thriller, Science Fiction, etc. 2. Sort the books Alphabetically within each Genre. 3. Present the categorized list in a clear and organized manner, using bullet points and numbering. """ # Function to call the Ollama model and generate categorized book list def categorize_books(model, prompt): """ Sends the prompt to the Ollama API and returns the categorized and sorted book list. """ try: response = ollama.generate(model=model, prompt=prompt) return response.get("response", "") except Exception as e: print("An error occurred while generating the response:", str(e)) return "" # Function to write the categorized book list to an output file def write_output(file_path, content): """ Writes the given content to the specified output file. """ with open(file_path, "w") as file: file.write(content.strip()) def main(): """ Main function to execute the categorization process. """ # Print the current working directory for debugging purposes print("Current Working Directory:", os.getcwd()) # Set the model and file paths model = "llama3.2" inputFile = "./data/bookList.txt" outputFile = "./data/bookListByCategory.txt" # Step 1: Check if the input file exists check_input_file(inputFile) # Step 2: Read the book list from the input file book_list = read_book_list(inputFile) # Step 3: Create the prompt to categorize books prompt = create_prompt(book_list) # Step 4: Categorize the books using the Ollama model categorized_books = categorize_books(model, prompt) if categorized_books: # Step 5: Write the categorized books to the output file write_output(outputFile, categorized_books) print(f"Categorized books are saved to '{outputFile}'") else: print("Failed to categorize books. Please check the error messages.") if __name__ == "__main__": main()
Output
Categorized books are saved to './data/bookListByCategory.txt' Open the file bookListByCategory.txt, you can see it contains below data. bookListByCategory.txt After categorizing and sorting the books, I present to you the list of genres with their corresponding titles: **Fantasy** 1. Beyond the Classroom: Reimagining Education for the Future 2. Champions Spirit: The Stories Behind the Victories 3. Guardians of the Ancient Flame 4. In the Footsteps of Giants 5. Laughter is the Best Medicine: Tales of Everyday Funny Moments 6. The Enchanted Kingdom of Everwood 7. The Lost City of Mirage 8. The Moonlit Voyager 9. The Shadows We Left Behind 10. Whispers in the Dark 11. Whispers of the Forgotten Forest 12. Wings of the Phoenix **Literary** 1. A Canvas for Creativity: Exploring Art's Boundaries 2. A Dance with Time 3. Codebreaker: The Future of AI and Data Security 4. Echoes of the Eternal Dawn 5. In the Footsteps of Giants 6. Living a Balanced Life: A Guide to Wellness 7. Savor: A Gourmet's Guide to Delicious Feasts 8. Tales from the Edge of the World 9. The Art of Living: A Journey Through Thought 10. The Gentle Guide: Raising Happy and Confident Children **Science Fiction** 1. Chronicles of the Nebula 2. Crossroads of Destiny 3. The Silent Witness 4. The Song of the Sea 5. The Secret of the Golden Key **Thriller/Mystery** 1. Cold Blooded: The Hunt for a Killer 2. Power Struggles: Politics in the 21st Century 3. The Curse of the Red Moon 4. The Silent City 5. Threads of Fate 6. Through His Eyes: The Life of an Artist **Non-Fiction/Informative** 1. A Journey Through Shadows 2. Beneath the Starry Sky 3. Codebreaker: The Future of AI and Data Security 4. Flavors of the World: A Culinary Adventure 5. Guardians of the Ancient Flame 6. In the Footsteps of Giants 7. Living a Balanced Life: A Guide to Wellness 8. Power Struggles: Politics in the 21st Century **Memoir/Biography** 1. Champions Spirit: The Stories Behind the Victories 2. Chronicles of the Nebula (Note: This title is more likely to be a work of non-fiction, but I've categorized it as memoir/biography for now) 3. Power Struggles: Politics in the 21st Century (Note: This title could also fit into other categories, but I've placed it here) **Poetry/Philosophical** 1. A Canvas for Creativity: Exploring Art's Boundaries 2. The Art of Living: A Journey Through Thought 3. Echoes of the Eternal Dawn Please note that some books may belong to multiple genres or have themes that span across multiple categories. This categorization is subjective and based on my best judgment. Let me know if you'd like any further clarification or adjustments!
By leveraging AI, you can effortlessly categorize and sort your book collection based on genres. Whether you are dealing with a few books or an extensive library, AI can streamline the entire process, making it more efficient and organized.
Now that you have a working solution, feel free to experiment with more complex book lists, or even apply this method to categorize other types of content. The possibilities are endless!
No comments:
Post a Comment