1
0
mirror of https://github.com/gsi-upm/senpy synced 2024-09-21 14:11:42 +00:00
senpy/sentiment-meaningCloud/sentiment-meaningCloud.py

76 lines
2.8 KiB
Python
Raw Normal View History

2017-01-12 12:30:14 +00:00
import time
import logging
2017-01-12 12:30:14 +00:00
import requests
import json
import string
import os
from os import path
import time
from senpy.plugins import SentimentPlugin, SenpyPlugin
2017-01-17 10:49:01 +00:00
from senpy.models import Results, Entry, Sentiment,Error
2017-01-12 12:30:14 +00:00
logger = logging.getLogger(__name__)
2017-01-12 12:30:14 +00:00
class DaedalusPlugin(SentimentPlugin):
def _polarity(self, value):
polarityValue = 0
polarity = 'marl:Neutral'
if 'N' in value:
polarity = 'marl:Negative'
polarityValue = -1
elif 'P' in value:
polarity = 'marl:Positive'
polarityValue = 1
return polarity, polarityValue
2017-01-12 12:30:14 +00:00
2017-02-28 13:27:18 +00:00
def analyse_entry(self, entry, params):
2017-01-12 12:30:14 +00:00
2017-02-28 13:27:18 +00:00
txt = entry.get("text",None)
2017-03-01 12:23:41 +00:00
model = "general" # general_es / general_es / general_fr
2017-01-12 12:30:14 +00:00
api = 'http://api.meaningcloud.com/sentiment-2.1'
lang = params.get("language")
2017-01-16 16:11:10 +00:00
key = params["apiKey"]
2017-03-01 12:23:41 +00:00
parameters = {'key': key,
'model': model,
'lang': lang,
'of': 'json',
'txt': txt,
'src': 'its-not-a-real-python-sdk'
}
try:
r = requests.post(api, params=parameters, timeout=3)
except requests.exceptions.Timeout:
raise Error("Meaning Cloud API does not response")
api_response = r.json()
if not api_response.get('score_tag'):
2017-01-17 10:49:01 +00:00
raise Error(r.json())
2017-01-12 12:30:14 +00:00
response = Results()
agg_polarity, agg_polarityValue = self._polarity(api_response.get('score_tag', None))
agg_opinion = Sentiment(id="Opinion0",
marl__hasPolarity=agg_polarity,
marl__polarityValue = agg_polarityValue,
marl__opinionCount = len(api_response['sentence_list']))
entry.sentiments.append(agg_opinion)
logger.info(api_response['sentence_list'])
count = 1
for sentence in api_response['sentence_list']:
for nopinion in sentence['segment_list']:
logger.info(nopinion)
polarity, polarityValue = self._polarity(nopinion.get('score_tag', None))
opinion = Sentiment(id="Opinion{}".format(count),
marl__hasPolarity=polarity,
marl__polarityValue=polarityValue,
marl__aggregatesOpinion=agg_opinion.get('id'),
nif__anchorOf=nopinion.get('text', None),
nif__beginIndex=nopinion.get('inip', None),
nif__endIndex=nopinion.get('endp', None)
)
2017-02-28 13:27:18 +00:00
count += 1
entry.sentiments.append(opinion)
yield entry