Sentiment Analysis Tool

Problem Statement

  • Company Type: E-commerce
  • Problem: E-commerce companies need to quickly and efficiently analyze customer sentiment based on user reviews, feedback, and social media to gauge perception of new or existing product launches.
  • Challenge: Large numbers of user sentiments need to be efficiently analyzed close to real-time to provide timely feedback to the business.

Technical Approach

Languages & Tools:
  • Backend Development: Python & Flask
  • Frontend Interaction: JavaScript
  • Sentiment Analysis: OpenAI’s GPT Model
  • API Integration: OpenAI Python Package
  • User Interface: HTML & CSS
  • Asynchronous Requests: AJAX, Axios, Fetch API
  • Data Handling: JSON

– **Process:**

  – Details on setting up the Flask app, integrating OpenAI API for sentiment analysis, and creating a user-friendly interface with JavaScript.

Setting Up the Flask App

1. Install Python:
– Download and install the latest version of Python from the official website.

  1. Navigate to Python’s Official Website: Go to [https://www.python.org/downloads/][1] to find the latest version of Python. As of the latest information, Python 3.12.2 is the most recent stable release14.
  2. Choose the Correct Installer: Select the appropriate installer for your operating system. For Windows, you can choose from the Windows installer (64-bit) or Windows installer (32-bit) depending on your system architecture4.
  3. Run the Installer: After downloading the installer, run it on your machine. During the installation process, make sure to check the option to “Add Python to PATH” to ensure that Python is accessible from the command line


2. Create a Virtual Environment:
– Open Command Prompt and navigate to your project directory.
– Create a virtual environment: `python -m venv venv`.

3. Activate the Virtual Environment:
– Activate the virtual environment:
– On Windows: `.\venv\Scripts\activate`.



4. Install Flask:
– Install Flask within the virtual environment: `pip install Flask`.

5. Create Your Flask Application:
– In your project directory, create a new file named `app.py`.
– Initialize the Flask app by adding:
“`python
from flask import Flask
app = Flask(__name__)

@app.route(‘/’)
def hello_world():
return ‘Hello, World!’
“`

6. Run Your Flask Application:
– In Command Prompt, navigate to your project directory.
– Run the Flask app: `flask run`.
– Access the app in a web browser at `http://127.0.0.1:5000/`.


7. Integrate OpenAI API:
– Install the OpenAI Python package: `pip install openai`.
– Set up an endpoint in your `app.py` for sentiment analysis, using the OpenAI API to process the text.


8. Create a User-Friendly Interface with JavaScript:
– In your project directory, create a `templates` folder for HTML files.
– Use HTML & CSS to design the frontend, and JavaScript to handle user interactions.
– Implement AJAX calls from the frontend to your Flask backend for sentiment analysis.

9. Test the Complete Application:
– Ensure the Flask app is running.
– Open the web interface, input text for sentiment analysis, and view the results.

Code Snippets

API integration

import openai
...
   chat_completion = client.chat.completions.create(
        messages=system + user,
        model="gpt-3.5-turbo",
        max_tokens=60,
        top_p=1.0,
    )

Sentiment Analysis Logic

    system = [
        {"role": "system", "content": "You are a sentiment analysis bot designed to analyze feedback on various features of e-commerce products. \
        Your task is to identify specific features mentioned in a piece of feedback, assess the sentiment for each feature individually, \
        and classify them as positive, negative, mixed, or ambiguous. You should return the analysis in JSON format. \
        For example:\
        Feedback: 'The camera quality of this smartphone is outstanding, capturing vibrant colors and details. However, the battery life is disappointing, barely lasting a day with moderate use.'\
        Response: {\
        'features': {\
            'camera quality': 'positive',\
            'battery life': 'negative'\
            }\
        }\
        Another example: \
        Feedback: 'The laptop's screen is bright and crisp, making it great for watching movies, but I've had mixed feelings about the keyboard's responsiveness.'\
        Response: {\
        'features': {\
            'screen': 'positive',\
            'keyboard responsiveness': 'mixed'\
            }\
        }\
        And: \
        Feedback: 'The product dimensions were not as described, which was confusing.'\
        Response: {\
        'features': {\
            'product dimensions': 'ambiguous'\
            }\
        }\
        Always use this structured approach to ensure clarity and precision in sentiment analysis."}
    ]

Front-End Code for Displaying Results

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sentiment Analysis Tool</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        #result { margin-top: 20px; }
    </style>
</head>
<body>
    <h1>Sentiment Analysis</h1>
    <textarea id="textInput" rows="4" cols="50" placeholder="Enter text here..."></textarea>
    <button onclick="analyzeText()">Analyze Sentiment</button>
    <div id="result"></div>

    <script>
        async function analyzeText() {
            const textInput = document.getElementById('textInput').value;
            const response = await fetch('/analyze', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ text: textInput })
            });
            const data = await response.json();
            document.getElementById('result').innerText = 'Sentiment: ' + data.sentiment;
        }
    </script>
</body>
</html>

Automatically Creating Brand-Aligned Ad Copy


Overview

  • Large language models like ChatGPT and Gemini are promising for generating ad copy efficiently.
  • The goal is to produce ad copy that aligns closely with approved copy, minimizing the need for refinement.
  • This blog post will discuss methods for creating ad copy that is consistent with the brand voice and adheres to best practices.
  • One of the key advantages of these models is their ability to consistently apply best practices to ensure high-quality outputs.
  • While generating copy quickly is achievable by many, maintaining consistent quality across all outputs is a common challenge.

What do you need?

  1. ChatGPT Plus Account – $20 / month (pricing)
  2. Understanding & agreement with your team about uploading existing ad copy to ChatGPT
  3. A review process for generated ad copy before it gets sent to the client / your boss.

Implementation Outline

  1. Sign up for ChatGPT Plus if you have not already
  2. Define internally what is ok / not ok to share with ChatGPT
  3. Setup a Custom GPT with existing approved ad copy
  4. Generate new ad copy

1. Signup for ChatGPT Plus

More information is available here on what the Plus plan is: https://openai.com/blog/chatgpt-plus

This video explains in a simple straightforward manner how to sign up for ChatGPT: https://www.youtube.com/watch?v=9HtgDtpo2co

Simple walkthrough on signing up for a Plus account: https://www.youtube.com/watch?v=9syn52pLU58

2. Define What is OK & Not OK to Share with ChatGPT

Your personal or organizational definitions might differ. Below is my opinion on what is okay and not okay to share with these large language models:

Not OK to Share:

  1. Anything that you would regret being made public if Openai or Google were to get hacked and the information was to be shared publicly.
  2. Any proprietary information such as financial records or brand updates not yet shared with the public.

OK to Share:

  1. Anonymized ad performance data
  2. Anything publicly available or already published on the internet

3. Setup a Custom GPT

These videos cover the basics of what a Custom GPT is & how to set it up:

Video 1: https://www.youtube.com/watch?v=5–JexprHuk

Video 2: https://www.youtube.com/watch?v=EWdCMPnm8uY

After watching the videos above you should have a pretty good understanding of what a custom GPT is as well as how to customize it or how we will customize it for our use.

To apply the above videos for our use case of generating automatic ad copy there are a few things to keep in mind.

CustomGPT’s at least for now are very use case specific

For me that this means that I have a custom GPT for each brand but specifically each brand, each ad platform and each component of the ad that I need to generate.

  1. customgpt_1_brand_1_google_ads_short_headlines
  2. customgpt_2_brand_1_google_ads_long_headlines
  3. customgpt_3_brand_1_google_ads_descriptions
  4. customgpt_4_brand_2_google_ads_short_headlines
  5. customgpt_5_brand_2_google_ads_long_headlines
  6. etc…

Why? Setting up in this segmented manner allows me to accomplish one of my main goals custom gpts which is to deliver best practice and highest level of work every time consistently.

We are also bound by the context window.

  • Current limitations restrict combining instructions for headline writing, description writing, and brand style guidelines into a single instruction set.
  • Approaching the context window limit decreases retrieval accuracy for essential information.
  • Upcoming updates will expand the context window, but for now, it’s crucial to manage content within existing constraints effectively.

Here is an example of how we would a set of custom GPT to write Google ads short headlines for the fictional company “Watson’s Zambonis”.

Name: Watson’s Zambonis – Google Ads – Short Headline

Description: A custom GPT that helps with writing Google ads short headlines for Watson’s Zambonis.

Instructions:

---

### Context
"You are a custom GPT trained to excel in creating compelling short headlines for Google search ads, with a deep understanding of search engine marketing, keyword optimization, and crafting impactful messages within tight character limits. You have access to a knowledge base containing files that define the brand guidelines and voice, as well as examples of previously approved ads that align with these standards."

### Requirement
"Generate short, attention-grabbing headlines for Google search ads that are relevant to the provided product or service description. Ensure the headlines not only adhere to Google's advertising policies and character count limits but also align with the brand's guidelines and voice as outlined in the knowledge base files. Incorporate key phrases effectively for SEO optimization."

### Ask
- "Given a brief description of a product or service, along with access to the brand's guidelines and previously approved ad examples, create five short headlines for Google search ads. Each headline should not exceed 30 characters."
- "Identify and incorporate one to two key phrases relevant to the product or service, ensuring the headlines are both SEO-friendly and consistent with the brand's messaging."
- "Reflect the unique value propositions or selling points as per the brand's guidelines, differentiating the product or service from competitors."

### Feedback
"After generating the headlines, review them to ensure they:
- Are in line with the brand's guidelines and voice, as detailed in the knowledge base.
- Address the target audience's needs or interests effectively, adhering to the brand's messaging strategy.
- Are concise, descriptive, and include a call to action or a sense of urgency, following the examples of previously approved content."

### Tone
"Your responses should maintain a professional and creative tone, ensuring the headlines are engaging, persuasive, and reflective of the brand's established voice and guidelines. The goal is to encourage potential customers to click through and learn more about the product or service while staying true to the brand's identity."

---

Knowledgebase Setup:

  • Upload a document containing:
    • Approved ad copy.
    • Website copy.
    • Brand guidelines.
  • This document should be dynamic, allowing for updates without changing the GPT’s instructions.
  • The document serves as a reference, streamlining the process by avoiding frequent updates to the GPT’s instructions and minimizing the need to review brand guidelines repeatedly.

Processing Inbound Faxed Purchased Orders Automatically with ChatGPT


Overview

In this blog post, we will explore an implementation for receiving purchase orders via fax (mFax), sending them to the ChatGPT API having them processed into a format that we can use, and then automatically import them into software such as QuickBooks.

If you are already receiving purchase orders for your fax it will be necessary to get them into a digital format using a service such as eFax which in addition to sending faxes via PDF can also allow us to connect via API to retrieve them programmatically. For ChatGPT we will be using the vision functionality. At the time of this writing is a very economical solution and alternative to some of the more expensive OCR software available today.

Existing Solutions often are expensive and require quite technical implementations here is a discussion about the pros and cons of different solutions for NetSuite as an example: Reddit Discussion.

What do you need?

  1. mFax Business account – $150 / month (pricing)
  2. ChatGPT API account – $20 / month (pricing) + API usage

Implementation Outline

  1. Sign up for both mFax Business & ChatGPT.
  2. Run a Python script to retrieve the latest fax.
  3. Send the latest fax to ChatGPT & ask it to process into a set format that Quickbooks / NetSuite can read.
  4. Receive the processed information.
  5. Send the processed information to Quickbooks / NetSuite

2. Run a Python script to retrieve the latest fax

Below is an example Python script that we would use to retrieve the latest fax from mFax:

import requests

# Replace 'your_api_key_here' with your actual Documo API key
api_key = 'your_api_key_here'
headers = {'Authorization': f'Bearer {api_key}'}

# Endpoint for listing received faxes, sorted by date in descending order to get the latest
list_url = 'https://api.documo.com/v1/faxes?sort=-received&limit=1'

list_response = requests.get(list_url, headers=headers)
if list_response.status_code == 200:
    latest_fax_id = list_response.json()['data'][0]['id']  # Assuming at least one fax is available
    print(f"Latest fax ID: {latest_fax_id}")

    # Endpoint to download the fax in PDF format
    download_url = f'https://api.documo.com/v1/faxes/{latest_fax_id}/content'
    download_response = requests.get(download_url, headers=headers, stream=True)

    if download_response.status_code == 200:
        with open(f'{latest_fax_id}.pdf', 'wb') as f:
            f.write(download_response.content)
        print(f"Fax {latest_fax_id} downloaded as PDF.")
    else:
        print("Failed to download fax. Status code:", download_response.status_code)
else:
    print("Failed to retrieve faxes. Status code:", list_response.status_code)

3. Send the Fax to ChatGPT Ask for a Readable Format

In this step we will be utilizing the ChatGPT API. Well it is possible to use the assistant API for this step it is relatively unnecessary for a simple direct task such as this.

Here is the example code for sending a PDF to Chachi PT and asking it to transcribe it into a format that will be readable by QuickBooks or NetSuite.

Outline Product Manuals with Copilot


Required

  1. Copilot subscription + Microsoft Word
  2. Identify Your Audience: Before using Copilot it will be helpful to define your audience including their technical expertise common questions, needs & preferences.

Using Copilot to Outline Product Manuals

Outline Structure: Writing to your intended audience ask Copilot to outline the table of contents first and then if you’d like go back and ask for chapter by chapter individually.

"Create an outline for a product manual for beginner-level users who have just purchased a radio and have no prior experience using one. The outline should specifically address the following aspects:

Common Questions:
How to install batteries or connect to a power source?
What are AM and FM, and how do they differ?
How to find and save radio stations?"

Helpful Videos:

  1. The Top 5 Super Powers of Copilot Pro (Jan 24, 2024) – 1 minute intro video (before launch last year)
  2. How to use COPILOT in Microsoft Word | Tutorial (Jan 23, 2024) – 8 minute tutorial
  3. How to use Copilot in Word to search, summarize and simplify complex documents (Jan 29, 2024) – (1:35) Quick use case from Microsoft