mirror of
https://github.com/gsi-upm/senpy
synced 2025-07-15 16:02:20 +00:00
* Fixed Options for extra_params in UI * Enhanced meta-programming for models * Plugins can be imported from a python file if they're named `senpy_<whatever>.py>` (no need for `.senpy` anymore!) * Add docstings and tests to most plugins * Read plugin description from the docstring * Refactor code to get rid of unnecessary `.senpy`s * Load models, plugins and utils into the main namespace (see __init__.py) * Enhanced plugin development/experience with utils (easy_test, easy_serve) * Fix bug in check_template that wouldn't check objects * Make model defaults a private variable * Add option to list loaded plugins in CLI * Update docs
67 lines
2.2 KiB
Python
67 lines
2.2 KiB
Python
import requests
|
|
import json
|
|
|
|
from senpy.plugins import SentimentPlugin
|
|
from senpy.models import Sentiment
|
|
|
|
|
|
class Sentiment140Plugin(SentimentPlugin):
|
|
'''Connects to the sentiment140 free API: http://sentiment140.com'''
|
|
def analyse_entry(self, entry, params):
|
|
lang = params["language"]
|
|
res = requests.post("http://www.sentiment140.com/api/bulkClassifyJson",
|
|
json.dumps({
|
|
"language": lang,
|
|
"data": [{
|
|
"text": entry['nif:isString']
|
|
}]
|
|
}))
|
|
p = params.get("prefix", None)
|
|
polarity_value = self.maxPolarityValue * int(
|
|
res.json()["data"][0]["polarity"]) * 0.25
|
|
polarity = "marl:Neutral"
|
|
neutral_value = self.maxPolarityValue / 2.0
|
|
if polarity_value > neutral_value:
|
|
polarity = "marl:Positive"
|
|
elif polarity_value < neutral_value:
|
|
polarity = "marl:Negative"
|
|
|
|
sentiment = Sentiment(
|
|
prefix=p,
|
|
marl__hasPolarity=polarity,
|
|
marl__polarityValue=polarity_value)
|
|
sentiment.prov__wasGeneratedBy = self.id
|
|
entry.sentiments = []
|
|
entry.sentiments.append(sentiment)
|
|
entry.language = lang
|
|
yield entry
|
|
|
|
def test(self, *args, **kwargs):
|
|
'''
|
|
To avoid calling the sentiment140 API, we will mock the results
|
|
from requests.
|
|
'''
|
|
from senpy.test import patch_requests
|
|
expected = {"data": [{"polarity": 10}]}
|
|
with patch_requests(expected) as (request, response):
|
|
super(Sentiment140Plugin, self).test(*args, **kwargs)
|
|
assert request.called
|
|
assert response.json.called
|
|
|
|
test_cases = [
|
|
{
|
|
'entry': {
|
|
'nif:isString': 'I love Titanic'
|
|
},
|
|
'params': {},
|
|
'expected': {
|
|
"nif:isString": "I love Titanic",
|
|
'sentiments': [
|
|
{
|
|
'marl:hasPolarity': 'marl:Positive',
|
|
}
|
|
]
|
|
}
|
|
}
|
|
]
|