Building Film Script Analyzer using Lyzr SDK
Tags: ai, lyzr, promptengineering, film
Published: 2024-03-28 19:12:32

Welcome to our **Film Script Analyzer** powered by 
**Lyzr SDK**! In this blog post, we’ll explore how this innovative tool can decode **film scripts**, helping you uncover the intricacies of storytelling, character motivations, thematic elements, and more.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hqzoph4qyx3u7befsu1i.png)

**Understanding the Tool** :

Our Film Script Analyzer is built using the **Lyzr SDK**, a powerful natural language processing tool designed to facilitate interaction with textual data. Leveraging cutting-edge technologies like **RAG** (Retrieval-Augmented Generation), this tool allows for seamless communication between users and the uploaded **PDF scripts**.

**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](https://docs.lyzr.ai/homepage)

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

```
import os
import streamlit as st
from lyzr import ChatBot
from utils import utils
```
The Python script utilizes the **os** module for operating system interaction, **streamlit** for building interactive web applications, and **lyzr** for chatbot functionality. Additionally, it references a **utils** module for auxiliary tasks.

Also the **utils.py** module likely contains utility functions for **handling file** operations within the application. These functions would likely include methods to **save uploaded files**, **retrieve files**, and **remove files** as needed. These operations are crucial for managing user input and ensuring proper handling of files throughout the application's workflow.

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.

```
# Set OpenAI API key
os.environ["OPENAI_API_KEY"] = st.secrets["apikey"]
```

```
# Function to initialize ChatBot for PDF files
def initialize_chatbot(file_path):
    vector_store_params = {
        "vector_store_type": "WeaviateVectorStore",
        "url": st.secrets["WEVIATE_URL"],
        "api_key": st.secrets["WEVIATE_API"],
        "index_name": f"File{file_path[0:4]}IndexName" 
    }
    chatbot = ChatBot.pdf_chat(input_files=[file_path], vector_store_params=vector_store_params)
    return chatbot
```
In this snippet the **initialize_chatbot** function initializes a chatbot specifically tailored for processing **PDF files**. It accepts a file_path argument indicating the path to the PDF file to be processed.

The function configures parameters for a **vector store**, including the type (WeaviateVectorStore), URL, API key, and index name based on the file path. Using these parameters, it initializes the chatbot using the pdf_chat method from the **ChatBot** class/module. Finally, it returns the initialized chatbot object, enabling interaction with PDF data through the specified vector store

```
def pdf_chat_integration():

    # Upload PDF file
    uploaded_file = st.file_uploader("Upload PDF script", type=['pdf'])
    if uploaded_file is not None:  # Check if file is uploaded
        st.success(f"File uploaded: {uploaded_file.name} (PDF)")
        st.markdown("### Pre-Prompts:")
        prompts = [
            "Can you provide a summary of the main characters' motivations and arcs?",
            "How does the setting contribute to the overall mood or atmosphere of the story?",
            "What thematic elements or messages does the script explore?",
            "What is the central conflict driving the narrative of the film?"
        ]
        
        # Display pre-defined prompts as buttons
        col1, col2 = st.columns(2)
        for i, prompt in enumerate(prompts):
            if i % 2 == 0:
                button = col1.button(prompt, key=f"button_{i}")
            else:
                button = col2.button(prompt, key=f"button_{i}")

            # Check if button is clicked
            if button:
                st.text("Processing...")
                file_path = utils.save_uploaded_file(uploaded_file)  # Save uploaded file
                if file_path is not None:  # Check if file is saved successfully
                    print("File saved at:", file_path)  # Print file path for debugging
                    chatbot = initialize_chatbot(file_path)
                    if chatbot:
                        response = chatbot.chat(prompt)  # Use selected prompt
                        st.text("Answer:")
                        st.write(response.response)
                    else:
                        st.error("Failed to initialize chatbot. Please try again.")

        question = st.text_input("Ask a question about the document:")
        if st.button("Get Answer"):
            st.text("Processing...")
            file_path = utils.save_uploaded_file(uploaded_file)  # Save uploaded file
            if file_path is not None:  # Check if file is saved successfully
                print("File saved at:", file_path)  # Print file path for debugging
                chatbot = initialize_chatbot(file_path)
                if chatbot:
                    response = chatbot.chat(question)  # Corrected method call
                    st.text("Answer:")
                    st.write(response.response)
                else:
                    st.error("Failed to initialize chatbot. Please try again.")
    else:
        utils.remove_existing_files(data)
        st.warning("Please upload a PDF file.")
```
The **pdf_chat_integration** function enables interaction with a PDF document by allowing users to upload a **PDF file** and ask questions about its content. It starts by providing an option to upload a PDF file, displaying **predefined prompts** as buttons for users to choose from.

Upon selecting a prompt, it saves the uploaded file and initializes a **chatbot** specifically designed for processing PDF files. It then retrieves a response from the chatbot based on the selected prompt and displays it to the user.

Additionally, users can ask **custom questions** about the document using a text input field, with the function providing responses based on the user's query. If no PDF file is uploaded, it prompts the user to do so. Overall, the function facilitates dynamic interaction with PDF documents through a **chatbot** interface.

Watch the tutorial : https://www.youtube.com/watch?v=3ifeNtqQu4A

**References**
Lyzr Website: [Lyzr](https://www.lyzr.ai/)

Book a Demo: [Demo](https://www.lyzr.ai/book-demo/)

Lyzr Community Channels: [Discord](https://discord.com/invite/nm7zSyEFA2)

Slack : [Slack](https://anybodycanai.slack.com/join/shared_invite/zt-2a7fr38f7-_QDOY1W1WSlSiYNAEncLGw#/shared-invite/email)