2016-08-11 09:40:42 +02:00
|
|
|
#!/usr/bin/env python2
|
|
|
|
# -*-coding:UTF-8 -*
|
|
|
|
"""
|
2016-08-13 15:24:57 +02:00
|
|
|
Sentiment analyser module.
|
2016-08-17 09:46:25 +02:00
|
|
|
It takes its inputs from 'global'.
|
2016-08-11 09:40:42 +02:00
|
|
|
|
2017-05-09 11:13:16 +02:00
|
|
|
The content is analysed if the length of the line is
|
|
|
|
above a defined threshold (get_p_content_with_removed_lines).
|
2016-08-17 09:46:25 +02:00
|
|
|
This is done because NLTK sentences tokemnizer (sent_tokenize) seems to crash
|
|
|
|
for long lines (function _slices_from_text line#1276).
|
|
|
|
|
|
|
|
|
|
|
|
nltk.sentiment.vader module credit:
|
|
|
|
Hutto, C.J. & Gilbert, E.E. (2014). VADER: A Parsimonious Rule-based Model for Sentiment Analysis of Social Media Text. Eighth International Conference on Weblogs and Social Media (ICWSM-14). Ann Arbor, MI, June 2014.
|
2016-08-11 09:40:42 +02:00
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
import time
|
2016-08-13 15:24:57 +02:00
|
|
|
import datetime
|
|
|
|
import calendar
|
|
|
|
import redis
|
2016-08-16 16:33:02 +02:00
|
|
|
import json
|
2016-08-11 09:40:42 +02:00
|
|
|
from pubsublogger import publisher
|
|
|
|
from Helper import Process
|
2016-08-13 15:24:57 +02:00
|
|
|
from packages import Paste
|
2016-08-11 09:40:42 +02:00
|
|
|
|
|
|
|
from nltk.sentiment.vader import SentimentIntensityAnalyzer
|
|
|
|
from nltk import tokenize
|
|
|
|
|
2016-08-16 16:33:02 +02:00
|
|
|
# Config Variables
|
|
|
|
accepted_Mime_type = ['text/plain']
|
2016-08-17 09:46:25 +02:00
|
|
|
size_threshold = 250
|
|
|
|
line_max_length_threshold = 1000
|
2016-08-11 09:40:42 +02:00
|
|
|
|
2017-01-11 11:00:36 +01:00
|
|
|
import os
|
|
|
|
import ConfigParser
|
|
|
|
|
|
|
|
configfile = os.path.join(os.environ['AIL_BIN'], 'packages/config.cfg')
|
|
|
|
if not os.path.exists(configfile):
|
|
|
|
raise Exception('Unable to find the configuration file. \
|
|
|
|
Did you set environment variables? \
|
|
|
|
Or activate the virtualenv.')
|
|
|
|
|
|
|
|
cfg = ConfigParser.ConfigParser()
|
|
|
|
cfg.read(configfile)
|
|
|
|
|
|
|
|
sentiment_lexicon_file = cfg.get("Directories", "sentiment_lexicon_file")
|
|
|
|
|
2016-08-13 15:24:57 +02:00
|
|
|
def Analyse(message, server):
|
2016-08-11 09:40:42 +02:00
|
|
|
path = message
|
2016-08-13 15:24:57 +02:00
|
|
|
paste = Paste.Paste(path)
|
|
|
|
|
2016-08-17 09:46:25 +02:00
|
|
|
# get content with removed line + number of them
|
|
|
|
num_line_removed, p_content = paste.get_p_content_with_removed_lines(line_max_length_threshold)
|
2016-08-13 15:24:57 +02:00
|
|
|
provider = paste.p_source
|
|
|
|
p_date = str(paste._get_p_date())
|
2016-08-16 16:33:02 +02:00
|
|
|
p_MimeType = paste._get_p_encoding()
|
|
|
|
|
|
|
|
# Perform further analysis
|
|
|
|
if p_MimeType == "text/plain":
|
2016-08-17 09:46:25 +02:00
|
|
|
if isJSON(p_content):
|
2016-08-16 16:33:02 +02:00
|
|
|
p_MimeType = "JSON"
|
|
|
|
|
|
|
|
if p_MimeType in accepted_Mime_type:
|
2016-08-17 09:46:25 +02:00
|
|
|
|
2016-08-16 16:33:02 +02:00
|
|
|
the_date = datetime.date(int(p_date[0:4]), int(p_date[4:6]), int(p_date[6:8]))
|
|
|
|
the_time = datetime.datetime.now()
|
|
|
|
the_time = datetime.time(getattr(the_time, 'hour'), 0, 0)
|
|
|
|
combined_datetime = datetime.datetime.combine(the_date, the_time)
|
|
|
|
timestamp = calendar.timegm(combined_datetime.timetuple())
|
2017-01-26 08:11:18 +01:00
|
|
|
|
2016-08-17 09:46:25 +02:00
|
|
|
sentences = tokenize.sent_tokenize(p_content.decode('utf-8', 'ignore'))
|
2017-01-26 08:11:18 +01:00
|
|
|
|
2016-08-17 09:46:25 +02:00
|
|
|
if len(sentences) > 0:
|
|
|
|
avg_score = {'neg': 0.0, 'neu': 0.0, 'pos': 0.0, 'compoundPos': 0.0, 'compoundNeg': 0.0}
|
|
|
|
neg_line = 0
|
|
|
|
pos_line = 0
|
2017-01-11 11:00:36 +01:00
|
|
|
sid = SentimentIntensityAnalyzer(sentiment_lexicon_file)
|
2016-08-17 09:46:25 +02:00
|
|
|
for sentence in sentences:
|
|
|
|
ss = sid.polarity_scores(sentence)
|
|
|
|
for k in sorted(ss):
|
|
|
|
if k == 'compound':
|
|
|
|
if ss['neg'] > ss['pos']:
|
|
|
|
avg_score['compoundNeg'] += ss[k]
|
|
|
|
neg_line += 1
|
|
|
|
else:
|
|
|
|
avg_score['compoundPos'] += ss[k]
|
|
|
|
pos_line += 1
|
2016-08-16 16:33:02 +02:00
|
|
|
else:
|
2016-08-17 09:46:25 +02:00
|
|
|
avg_score[k] += ss[k]
|
2017-01-26 08:11:18 +01:00
|
|
|
|
|
|
|
|
2016-08-17 09:46:25 +02:00
|
|
|
for k in avg_score:
|
|
|
|
if k == 'compoundPos':
|
|
|
|
avg_score[k] = avg_score[k] / (pos_line if pos_line > 0 else 1)
|
|
|
|
elif k == 'compoundNeg':
|
|
|
|
avg_score[k] = avg_score[k] / (neg_line if neg_line > 0 else 1)
|
|
|
|
else:
|
|
|
|
avg_score[k] = avg_score[k] / len(sentences)
|
2017-01-26 08:11:18 +01:00
|
|
|
|
|
|
|
|
2016-08-17 09:46:25 +02:00
|
|
|
# In redis-levelDB: {} = set, () = K-V
|
|
|
|
# {Provider_set -> provider_i}
|
|
|
|
# {Provider_TimestampInHour_i -> UniqID_i}_j
|
|
|
|
# (UniqID_i -> PasteValue_i)
|
2017-01-26 08:11:18 +01:00
|
|
|
|
2016-08-17 09:46:25 +02:00
|
|
|
server.sadd('Provider_set', provider)
|
2017-01-26 08:11:18 +01:00
|
|
|
|
2016-08-17 09:46:25 +02:00
|
|
|
provider_timestamp = provider + '_' + str(timestamp)
|
|
|
|
server.incr('UniqID')
|
|
|
|
UniqID = server.get('UniqID')
|
|
|
|
print provider_timestamp, '->', UniqID, 'dropped', num_line_removed, 'lines'
|
|
|
|
server.sadd(provider_timestamp, UniqID)
|
|
|
|
server.set(UniqID, avg_score)
|
2016-08-16 16:33:02 +02:00
|
|
|
else:
|
|
|
|
print 'Dropped:', p_MimeType
|
2017-01-26 08:11:18 +01:00
|
|
|
|
2016-08-16 16:33:02 +02:00
|
|
|
|
|
|
|
def isJSON(content):
|
|
|
|
try:
|
|
|
|
json.loads(content)
|
|
|
|
return True
|
|
|
|
|
|
|
|
except Exception,e:
|
|
|
|
return False
|
2016-08-11 09:40:42 +02:00
|
|
|
|
2017-01-26 08:11:18 +01:00
|
|
|
import signal
|
|
|
|
|
|
|
|
class TimeoutException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
def timeout_handler(signum, frame):
|
|
|
|
raise TimeoutException
|
|
|
|
|
|
|
|
signal.signal(signal.SIGALRM, timeout_handler)
|
|
|
|
|
2016-08-11 09:40:42 +02:00
|
|
|
if __name__ == '__main__':
|
|
|
|
# If you wish to use an other port of channel, do not forget to run a subscriber accordingly (see launch_logs.sh)
|
|
|
|
# Port of the redis instance used by pubsublogger
|
|
|
|
publisher.port = 6380
|
|
|
|
# Script is the default channel used for the modules.
|
|
|
|
publisher.channel = 'Script'
|
|
|
|
|
|
|
|
# Section name in bin/packages/modules.cfg
|
2016-08-16 16:33:02 +02:00
|
|
|
config_section = 'SentimentAnalysis'
|
2016-08-11 09:40:42 +02:00
|
|
|
|
|
|
|
# Setup the I/O queues
|
|
|
|
p = Process(config_section)
|
|
|
|
|
|
|
|
# Sent to the logging a description of the module
|
|
|
|
publisher.info("<description of the module>")
|
|
|
|
|
2016-08-13 15:24:57 +02:00
|
|
|
# REDIS_LEVEL_DB #
|
|
|
|
server = redis.StrictRedis(
|
|
|
|
host=p.config.get("Redis_Level_DB_Sentiment", "host"),
|
|
|
|
port=p.config.get("Redis_Level_DB_Sentiment", "port"),
|
|
|
|
db=p.config.get("Redis_Level_DB_Sentiment", "db"))
|
|
|
|
|
2016-08-11 09:40:42 +02:00
|
|
|
while True:
|
|
|
|
message = p.get_from_set()
|
|
|
|
if message is None:
|
|
|
|
publisher.debug("{} queue is empty, waiting".format(config_section))
|
|
|
|
time.sleep(1)
|
|
|
|
continue
|
2017-01-26 08:11:18 +01:00
|
|
|
signal.alarm(60)
|
|
|
|
try:
|
|
|
|
Analyse(message, server)
|
|
|
|
except TimeoutException:
|
|
|
|
print ("{0} processing timeout".format(message))
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
signal.alarm(0)
|
2016-08-17 09:46:25 +02:00
|
|
|
|