Skip to content

Instantly share code, notes, and snippets.

@kagesenshi
Created April 15, 2023 09:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kagesenshi/82fa02e989ed0e39e19e1a4ec25c5d1b to your computer and use it in GitHub Desktop.
Save kagesenshi/82fa02e989ed0e39e19e1a4ec25c5d1b to your computer and use it in GitHub Desktop.
ChatGPT Sentiment Analyzer
import openai
class SentimentAnalyzer(object):
def __init__(self, language):
self._language = language
def _prompt(self):
prompt = """
The following sentence is in %s language.
Categorize the sentence in to good, bad, neutral or sarcastic sentiment.
Provide output in the form of JSONL without any wrapping text. Valid
return values are "positive", "negative", "neutral", "sarcastic". Also include
the sentence in the json. Do not provide any explanation so that the result can
be parsed by json parser.
""" % self._language
return prompt
def evaluate(self, messages):
prompt = self._prompt() + "\n".join(messages)
completion = openai.ChatCompletion.create(model='gpt-3.5-turbo', messages=[{'role': 'user', 'content': prompt}])
return completion.choices[0].message.content
analyzer = SentimentAnalyzer('malay')
print(analyzer.evaluate(messages=['tak boleh blah']))
print(analyzer.evaluate(messages=['tak suka makan', 'ye la tu, suka la sangat', 'jom makan']))
@kagesenshi
Copy link
Author

kagesenshi commented Apr 15, 2023

seems to handle sarcasm ok

$ export OPENAI_API_KEY="sk-...."
$ ./bin/python sentiment.py
{"sentence": "tak boleh blah", "sentiment": "negative"}
{"sentence": "tak suka makan", "sentiment": "negative"}
{"sentence": "ye la tu, suka la sangat", "sentiment": "sarcastic"}
{"sentence": "jom makan", "sentiment": "positive"}

@MazizEsa
Copy link

lol. xD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment