1
0
mirror of https://github.com/gsi-upm/senpy synced 2025-09-18 04:22:21 +00:00

Compare commits

..

22 Commits

Author SHA1 Message Date
J. Fernando Sánchez
1302b0b93c Fixed pip tests (added version) 2017-04-04 11:42:18 +02:00
J. Fernando Sánchez
ad1092690b Merge branch '20-improve-docs' into 0.8.x 2017-04-04 11:26:33 +02:00
J. Fernando Sánchez
e35e810ede Rephrase info on demo plugins
Closes #20
2017-04-04 11:26:05 +02:00
militarpancho
d5ddcb8d3f Change repository url 2017-04-04 11:21:08 +02:00
militarpancho
54c0c9c437 demo doc changed 2017-04-04 11:14:51 +02:00
J. Fernando Sánchez
6e970d01f2 Merge branch '21-ascii-cant-encode' into 0.8.x 2017-04-04 11:12:39 +02:00
J. Fernando Sánchez
1d0a54ecd2 Merge branch '22-pip-screws-with-logging-config' into 0.8.x 2017-04-04 11:12:23 +02:00
J. Fernando Sánchez
800d4a9c2c Fixed typos in Ian's patch 2017-04-04 11:11:51 +02:00
drevicko
035ef98b7e removed broken "/api" link
In index.html, there is a suggestion to try out the api with a link to "/api". Clicking that link results in a json error report - not ideal. 
Instead, I added text suggesting that a use can find example api url's after clickgin "Analyse!".
2017-04-04 11:07:32 +02:00
J. Fernando Sánchez
d7e115d7c2 Encode HEADERS
Closes #21
2017-04-03 19:23:18 +02:00
J. Fernando Sánchez
548cb4c9ba Doc changes
* Alabaster theme
* Restructured
* Simplified introduction
* Reference to entries/models
* Fixed examples
2017-04-03 18:20:09 +02:00
J. Fernando Sánchez
7e5b55ff9c Run pip with Popen
Closes #22
2017-03-30 17:38:17 +02:00
militarpancho
8b2c3e8d40 Update readthedocs. Mainly Api and What is senpy section 2017-03-28 12:34:39 +02:00
J. Fernando Sánchez
0c8f98d466 Pre-0.8.6
* Improved debugging (back to using Flask's built-in mechanisms)
* Recursive model loading from json
* Added DEVPORT to Makefile
* Accept json-ld input. Closes #16
* Improved Exception handling in client
* Modified default plugin selection to only include analysis plugins
* More tests
2017-03-14 19:59:06 +01:00
J. Fernando Sánchez
cc298742ec Merge branch '17-...' into 0.8.x 2017-03-14 13:20:20 +01:00
J. Fernando Sánchez
250052fb99 Options as a set in the JSON-LD context
Closes #18
2017-03-14 13:17:47 +01:00
J. Fernando Sánchez
603e086606 Fix list of plugins
Closes #17
2017-03-14 13:05:52 +01:00
J. Fernando Sánchez
a8614bab0c Accept plugin pipelines
Closes #15
2017-03-13 21:08:21 +01:00
J. Fernando Sánchez
70ca74b03c Added instructions for developers 2017-03-09 00:04:02 +01:00
J. Fernando Sánchez
c9e6d78183 Fixed alises, added PAD and FSRE
Closes #13
2017-03-08 23:23:40 +01:00
J. Fernando Sánchez
1a582c0843 Filter conversion plugins
Closes #12

* Shows only analysis plugins by default on /api/plugins
* Adds a plugin_type parameter to get other types of plugins
* default_plugin chosen from analysis plugins
2017-03-08 22:54:57 +01:00
drevicko
0394bcd69c add make version to readme for pip install
pip install needs the VERSION file - `make version` will create that file

I also added the -U flag to pip install to force install (this is important if the user is playing with the code or trying out different older versions, as pip will not install if it thinks the git repo represents a version already installed or older than the one installed)
2017-03-02 11:08:02 +00:00
33 changed files with 793 additions and 418 deletions

View File

@@ -6,6 +6,7 @@ VERSION=$(shell git describe --tags --dirty 2>/dev/null)
TARNAME=$(NAME)-$(VERSION).tar.gz TARNAME=$(NAME)-$(VERSION).tar.gz
IMAGENAME=$(REPO)/$(NAME) IMAGENAME=$(REPO)/$(NAME)
IMAGEWTAG=$(IMAGENAME):$(VERSION) IMAGEWTAG=$(IMAGENAME):$(VERSION)
DEVPORT=5000
action="test-${PYMAIN}" action="test-${PYMAIN}"
all: build run all: build run
@@ -43,7 +44,7 @@ quick_test: $(addprefix test-,$(PYMAIN))
dev-%: dev-%:
@docker start $(NAME)-dev$* || (\ @docker start $(NAME)-dev$* || (\
$(MAKE) build-$*; \ $(MAKE) build-$*; \
docker run -d -w /usr/src/app/ -v $$PWD:/usr/src/app --entrypoint=/bin/bash -ti --name $(NAME)-dev$* '$(IMAGEWTAG)-python$*'; \ docker run -d -w /usr/src/app/ -p $(DEVPORT):5000 -v $$PWD:/usr/src/app --entrypoint=/bin/bash -ti --name $(NAME)-dev$* '$(IMAGEWTAG)-python$*'; \
)\ )\
docker exec -ti $(NAME)-dev$* bash docker exec -ti $(NAME)-dev$* bash
@@ -57,8 +58,10 @@ test-%: build-%
test: test-$(PYMAIN) test: test-$(PYMAIN)
dist/$(TARNAME): dist/$(TARNAME): version
docker run --rm -ti -v $$PWD:/usr/src/app/ -w /usr/src/app/ python:$(PYMAIN) python setup.py sdist; docker run --rm -ti -v $$PWD:/usr/src/app/ -w /usr/src/app/ python:$(PYMAIN) python setup.py sdist;
docker run --rm -ti -v $$PWD:/usr/src/app/ -w /usr/src/app/ python:$(PYMAIN) chmod -R a+rwx dist;
sdist: dist/$(TARNAME) sdist: dist/$(TARNAME)
@@ -82,11 +85,11 @@ git_tag:
git_push: git_push:
git push --tags origin master git push --tags origin master
pip_upload: pip_upload: pip_test
python setup.py sdist upload ; python setup.py sdist upload ;
run-%: build-% run-%: build-%
docker run --rm -p 5000:5000 -ti '$(IMAGEWTAG)-python$(PYMAIN)' --default-plugins docker run --rm -p $(DEVPORT):5000 -ti '$(IMAGEWTAG)-python$(PYMAIN)' --default-plugins
run: run-$(PYMAIN) run: run-$(PYMAIN)

View File

@@ -23,7 +23,7 @@ Through PIP
.. code:: bash .. code:: bash
pip install --user senpy pip install -U --user senpy
Alternatively, you can use the development version: Alternatively, you can use the development version:
@@ -42,6 +42,53 @@ Build the image or use the pre-built one: ``docker run -ti -p 5000:5000 gsiupm/s
To add custom plugins, add a volume and tell senpy where to find the plugins: ``docker run -ti -p 5000:5000 -v <PATH OF PLUGINS>:/plugins gsiupm/senpy --default-plugins -f /plugins`` To add custom plugins, add a volume and tell senpy where to find the plugins: ``docker run -ti -p 5000:5000 -v <PATH OF PLUGINS>:/plugins gsiupm/senpy --default-plugins -f /plugins``
Developing
----------
Developing/debugging
********************
This command will run the senpy container using the latest image available, mounting your current folder so you get your latest code:
.. code:: bash
# Python 3.5
make dev
# Python 2.7
make dev-2.7
Building a docker image
***********************
.. code:: bash
# Python 3.5
make build-3.5
# Python 2.7
make build-2.7
Testing
*******
.. code:: bash
make test
Running
*******
This command will run the senpy server listening on localhost:5000
.. code:: bash
# Python 3.5
make run-3.5
# Python 2.7
make run-2.7
Usage Usage
----- -----
@@ -49,12 +96,14 @@ However, the easiest and recommended way is to just use the command-line tool to
.. code:: bash .. code:: bash
senpy senpy
or, alternatively: or, alternatively:
.. code:: bash .. code:: bash
python -m senpy python -m senpy

BIN
docs/_static/header.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

View File

@@ -1,5 +1,5 @@
NIF API NIF API
======= -------
.. http:get:: /api .. http:get:: /api
Basic endpoint for sentiment/emotion analysis. Basic endpoint for sentiment/emotion analysis.
@@ -22,38 +22,32 @@ NIF API
Content-Type: text/javascript Content-Type: text/javascript
{ {
"@context": [ "@context":"http://127.0.0.1/api/contexts/Results.jsonld",
"http://127.0.0.1/static/context.jsonld", "@id":"_:Results_11241245.22",
], "@type":"results"
"analysis": [ "analysis": [
{ "plugins/sentiment-140_0.1"
"@id": "SentimentAnalysisExample", ],
"@type": "marl:SentimentAnalysis", "entries": [
"dc:language": "en", {
"marl:maxPolarityValue": 10.0, "@id": "_:Entry_11241245.22"
"marl:minPolarityValue": 0.0 "@type":"entry",
} "emotions": [],
], "entities": [],
"domain": "wndomains:electronics", "sentiments": [
"entries": [ {
{ "@id": "Sentiment0",
"opinions": [ "@type": "sentiment",
{ "marl:hasPolarity": "marl:Negative",
"prov:generatedBy": "SentimentAnalysisExample", "marl:polarityValue": 0,
"marl:polarityValue": 7.8, "prefix": ""
"marl:hasPolarity": "marl:Positive", }
"marl:describesObject": "http://www.gsi.dit.upm.es", ],
} "suggestions": [],
], "text": "This text makes me sad.\nwhilst this text makes me happy and surprised at the same time.\nI cannot believe it!",
"nif:isString": "I love GSI", "topics": []
"strings": [ }
{ ]
"nif:anchorOf": "GSI",
"nif:taIdentRef": "http://www.gsi.dit.upm.es"
}
]
}
]
} }
:query i input: No default. Depends on informat and intype :query i input: No default. Depends on informat and intype
@@ -92,58 +86,59 @@ NIF API
.. sourcecode:: http .. sourcecode:: http
{ {
"@context": { "@id": "plugins/sentiment-140_0.1",
... "@type": "sentimentPlugin",
}, "author": "@balkian",
"@type": "plugins", "description": "Sentiment classifier using rule-based classification for English and Spanish. This plugin uses sentiment140 data to perform classification. For more information: http://help.sentiment140.com/for-students/",
"plugins": [ "extra_params": {
{ "language": {
"name": "sentiment140", "@id": "lang_sentiment140",
"is_activated": true, "aliases": [
"version": "0.1", "language",
"extra_params": { "l"
"@id": "extra_params_sentiment140_0.1", ],
"language": { "options": [
"required": false, "es",
"@id": "lang_sentiment140", "en",
"options": [ "auto"
"es", ],
"en", "required": false
"auto" }
], },
"aliases": [ "is_activated": true,
"language", "maxPolarityValue": 1.0,
"l" "minPolarityValue": 0.0,
] "module": "sentiment-140",
} "name": "sentiment-140",
}, "requirements": {},
"@id": "sentiment140_0.1" "version": "0.1"
}, { },
"name": "rand", {
"is_activated": true, "@id": "plugins/ExamplePlugin_0.1",
"version": "0.1", "@type": "sentimentPlugin",
"extra_params": { "author": "@balkian",
"@id": "extra_params_rand_0.1", "custom_attribute": "42",
"language": { "description": "I am just an example",
"required": false, "extra_params": {
"@id": "lang_rand", "parameter": {
"options": [ "@id": "parameter",
"es", "aliases": [
"en", "parameter",
"auto" "param"
], ],
"aliases": [ "default": 42,
"language", "required": true
"l" }
] },
} "is_activated": true,
}, "maxPolarityValue": 1.0,
"@id": "rand_0.1" "minPolarityValue": 0.0,
} "module": "example",
] "name": "ExamplePlugin",
} "requirements": "noop",
"version": "0.1"
}
.. http:get:: /api/plugins/<pluginname> .. http:get:: /api/plugins/<pluginname>
@@ -162,30 +157,60 @@ NIF API
.. sourcecode:: http .. sourcecode:: http
{ {
"@id": "rand_0.1", "@context": "http://127.0.0.1/api/contexts/ExamplePlugin.jsonld",
"@type": "sentimentPlugin", "@id": "plugins/ExamplePlugin_0.1",
"extra_params": { "@type": "sentimentPlugin",
"@id": "extra_params_rand_0.1", "author": "@balkian",
"language": { "custom_attribute": "42",
"@id": "lang_rand", "description": "I am just an example",
"aliases": [ "extra_params": {
"language", "parameter": {
"l" "@id": "parameter",
], "aliases": [
"options": [ "parameter",
"es", "param"
"en", ],
"auto" "default": 42,
], "required": true
"required": false }
} },
}, "is_activated": true,
"is_activated": true, "maxPolarityValue": 1.0,
"name": "rand", "minPolarityValue": 0.0,
"version": "0.1" "module": "example",
"name": "ExamplePlugin",
"requirements": "noop",
"version": "0.1"
} }
.. http:get:: /api/plugins/default .. http:get:: /api/plugins/default
Return the information about the default plugin. Return the information about the default plugin.

7
docs/apischema.rst Normal file
View File

@@ -0,0 +1,7 @@
API and Schema
##############
.. toctree::
vocabularies.rst
api.rst
schema.rst

15
docs/architecture.rst Normal file
View File

@@ -0,0 +1,15 @@
Architecture
============
The main component of a sentiment analysis service is the algorithm itself. However, for the algorithm to work, it needs to get the appropriate parameters from the user, format the results according to the defined API, interact with the user whn errors occur or more information is needed, etc.
Senpy proposes a modular and dynamic architecture that allows:
* Implementing different algorithms in a extensible way, yet offering a common interface.
* Offering common services that facilitate development, so developers can focus on implementing new and better algorithms.
The framework consists of two main modules: Senpy core, which is the building block of the service, and Senpy plugins, which consist of the analysis algorithm. The next figure depicts a simplified version of the processes involved in an analysis with the Senpy framework.
.. image:: senpy-architecture.png
:width: 100%
:align: center

View File

@@ -37,6 +37,7 @@ extensions = [
'sphinx.ext.todo', 'sphinx.ext.todo',
'sphinxcontrib.httpdomain', 'sphinxcontrib.httpdomain',
'sphinx.ext.coverage', 'sphinx.ext.coverage',
'sphinx.ext.autosectionlabel'
] ]
# Add any paths that contain templates here, relative to this directory. # Add any paths that contain templates here, relative to this directory.
@@ -54,20 +55,21 @@ master_doc = 'index'
# General information about the project. # General information about the project.
project = u'Senpy' project = u'Senpy'
copyright = u'2016, J. Fernando Sánchez' copyright = u'2016, J. Fernando Sánchez'
description = u'A framework for sentiment and emotion analysis services'
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the # |version| and |release|, also used in various other places throughout the
# built documents. # built documents.
# #
# The short X.Y version. # The short X.Y version.
with open('../senpy/VERSION') as f: # with open('../senpy/VERSION') as f:
version = f.read().strip() # version = f.read().strip()
# The full version, including alpha/beta/rc tags. # The full version, including alpha/beta/rc tags.
release = version # release = version
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages. # for a list of supported languages.
#language = None language = None
# There are two options for replacing |today|: either, you set today to some # There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used: # non-false value, then it is used:
@@ -104,14 +106,14 @@ pygments_style = 'sphinx'
#keep_warnings = False #keep_warnings = False
html_theme = 'alabaster'
# -- Options for HTML output ---------------------------------------------- # -- Options for HTML output ----------------------------------------------
if not on_rtd: # only import and set the theme if we're building docs locally # if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme # import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme' # html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
else: # else:
html_theme = 'default' # html_theme = 'default'
# The theme to use for HTML and HTML Help pages. See the documentation for # The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes. # a list of builtin themes.
@@ -119,7 +121,13 @@ else:
# Theme options are theme-specific and customize the look and feel of a theme # Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the # further. For a list of options available for each theme, see the
# documentation. # documentation.
#html_theme_options = {} html_theme_options = {
'logo': 'header.png',
'github_user': 'gsi-upm',
'github_repo': 'senpy',
'github_banner': True,
}
# Add any paths that contain custom themes here, relative to this directory. # Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = [] #html_theme_path = []
@@ -159,7 +167,13 @@ html_static_path = ['_static']
#html_use_smartypants = True #html_use_smartypants = True
# Custom sidebar templates, maps document names to template names. # Custom sidebar templates, maps document names to template names.
#html_sidebars = {} html_sidebars = {
'**': [
'about.html',
'navigation.html',
'searchbox.html',
]
}
# Additional templates that should be rendered to pages, maps page names to # Additional templates that should be rendered to pages, maps page names to
# template names. # template names.

View File

@@ -1,7 +1,8 @@
Demo Demo
---- ----
There is a demo available on http://senpy.demos.gsi.dit.upm.es/, where you can a serie of different plugins. You can use them in the playground or make a directly requests to the service. There is a demo available on http://senpy.cluster.gsi.dit.upm.es/, where you can test a serie of different plugins.
You can use the playground (a web interface) or make HTTP requests to the service API.
.. image:: senpy-playground.png .. image:: senpy-playground.png
:height: 400px :height: 400px
@@ -12,64 +13,4 @@ There is a demo available on http://senpy.demos.gsi.dit.upm.es/, where you can a
Plugins Demo Plugins Demo
============ ============
The next plugins are available at the demo: The source code and description of the plugins used in the demo is available here: https://lab.cluster.gsi.dit.upm.es/senpy/senpy-plugins-community/.
* emoTextAnew extracts the VAD (valence-arousal-dominance) of a sentence by matching words from the ANEW dictionary.
* emoTextWordnetAffect based on the hierarchy of WordnetAffect to calculate the emotion of the sentence.
* vaderSentiment utilizes the software from vaderSentiment to calculate the sentiment of a sentence.
* sentiText is a software developed during the TASS 2015 competition, it has been adapted for English and Spanish.
emoTextANEW plugin
******************
This plugin is going to used the ANEW lexicon dictionary to calculate de VAD (valence-arousal-dominance) of the sentence and the determinate which emotion is closer to this value.
Each emotion has a centroid, which it has been approximated using the formula described in this article:
http://www.aclweb.org/anthology/W10-0208
The plugin is going to look for the words in the sentence that appear in the ANEW dictionary and calculate the average VAD score for the sentence. Once this score is calculated, it is going to seek the emotion that is closest to this value.
emoTextWAF plugin
*****************
This plugin uses WordNet-Affect (http://wndomains.fbk.eu/wnaffect.html) to calculate the percentage of each emotion. The emotions that are going to be used are: anger, fear, disgust, joy and sadness. It is has been used a emotion mapping enlarge the emotions:
* anger : general-dislike
* fear : negative-fear
* disgust : shame
* joy : gratitude, affective, enthusiasm, love, joy, liking
* sadness : ingrattitude, daze, humlity, compassion, despair, anxiety, sadness
sentiText plugin
****************
This plugin is based in the classifier developed for the TASS 2015 competition. It has been developed for Spanish and English. The different phases that has this plugin when it is activated:
* Train both classifiers (English and Spanish).
* Initialize resources (dictionaries,stopwords,etc.).
* Extract bag of words,lemmas and chars.
Once the plugin is activated, the features that are going to be extracted for the classifiers are:
* Matches with the bag of words extracted from the train corpus.
* Sentiment score of the sentences extracted from the dictionaries (lexicons and emoticons).
* Identify negations and intensifiers in the sentences.
* Complementary features such as exclamation and interrogation marks, eloganted and caps words, hashtags, etc.
The plugin has a preprocessor, which is focues on Twitter corpora, that is going to be used for cleaning the text to simplify the feature extraction.
There is more information avaliable in the next article.
Aspect based Sentiment Analysis of Spanish Tweets, Oscar Araque and Ignacio Corcuera-Platas and Constantino Román-Gómez and Carlos A. Iglesias and J. Fernando Sánchez-Rada. http://gsi.dit.upm.es/es/investigacion/publicaciones?view=publication&task=show&id=37
vaderSentiment plugin
*********************
For developing this plugin, it has been used the module vaderSentiment, which is described in the paper: VADER: A Parsimonious Rule-based Model for Sentiment Analysis of Social Media Text C.J. Hutto and Eric Gilbert Eighth International Conference on Weblogs and Social Media (ICWSM-14). Ann Arbor, MI, June 2014.
If you use this plugin in your research, please cite the above paper
For more information about the functionality, check the official repository
https://github.com/cjhutto/vaderSentiment

View File

@@ -1,15 +1,28 @@
Welcome to Senpy's documentation! Welcome to Senpy's documentation!
================================= =================================
Contents: With Senpy, you can easily turn your sentiment or emotion analysis algorithm into a full blown semantic service.
Sharing your sentiment analysis with the world has never been easier.
Senpy provides:
* Parameter validation, error handling
* Formatting: JSON-LD, Turtle/n-triples input and output, or simple text input
* Linked Data. Results are semantically annotated, using a series of well established vocabularies, and sane default URIs.
* A web UI where users can explore your service and test different settings
* A client to interact with any senpy service
* A command line tool
.. toctree:: .. toctree::
:caption: Learn more about senpy
:maxdepth: 2
senpy senpy
installation installation
usage usage
api apischema
schema
plugins plugins
conversion conversion
demo demo
:maxdepth: 2 research.rst

View File

@@ -22,6 +22,35 @@ If you want to install senpy globally, use sudo instead of the ``--user`` flag.
Docker Image Docker Image
************ ************
Build the image or use the pre-built one: ``docker run -ti -p 5000:5000 gsiupm/senpy --host 0.0.0.0 --default-plugins``. Build the image or use the pre-built one:
.. code:: bash
docker run -ti -p 5000:5000 gsiupm/senpy --host 0.0.0.0 --default-plugins
To add custom plugins, use a docker volume:
.. code:: bash
docker run -ti -p 5000:5000 -v <PATH OF PLUGINS>:/plugins gsiupm/senpy --host 0.0.0.0 --default-plugins -f /plugins
Alias
.....
If you are using the docker approach regularly, it is advisable to use a script or an alias to simplify your executions:
.. code:: bash
alias senpy='docker run --rm -ti -p 5000:5000 -v $PWD:/senpy-plugins gsiupm/senpy --default-plugins'
Python 2
........
There is a Senpy version for python2 too:
.. code:: bash
docker run -ti -p 5000:5000 gsiupm/senpy:python2.7 --host 0.0.0.0 --default-plugins
To add custom plugins, add a volume and tell senpy where to find the plugins: ``docker run -ti -p 5000:5000 -v <PATH OF PLUGINS>:/plugins gsiupm/senpy --host 0.0.0.0 --default-plugins -f /plugins``

View File

@@ -2,27 +2,34 @@ Developing new plugins
---------------------- ----------------------
This document describes how to develop a new analysis plugin. For an example of conversion plugins, see :doc:`conversion`. This document describes how to develop a new analysis plugin. For an example of conversion plugins, see :doc:`conversion`.
Each plugin represents a different analysis process.There are two types of files that are needed by senpy for loading a plugin: A more step-by-step tutorial with slides is available `here <https://lab.cluster.gsi.dit.upm.es/senpy/senpy-tutorial>`__
- Definition file, has the ".senpy" extension. What is a plugin?
- Code file, is a python file. =================
This separation will allow us to deploy plugins that use the same code but employ different parameters. A plugin is a program that, given a text, will add annotations to it.
In practice, a plugin consists of at least two files:
- Definition file: a `.senpy` file that describes the plugin (e.g. what input parameters it accepts, what emotion model it uses).
- Python module: the actual code that will add annotations to each input.
This separation allows us to deploy plugins that use the same code but employ different parameters.
For instance, one could use the same classifier and processing in several plugins, but train with different datasets. For instance, one could use the same classifier and processing in several plugins, but train with different datasets.
This scenario is particularly useful for evaluation purposes. This scenario is particularly useful for evaluation purposes.
The only limitation is that the name of each plugin needs to be unique. The only limitation is that the name of each plugin needs to be unique.
Plugins Definitions Plugin Definition files
=================== =======================
The definition file contains all the attributes of the plugin, and can be written in YAML or JSON. The definition file contains all the attributes of the plugin, and can be written in YAML or JSON.
When the server is launched, it will recursively search for definition files in the plugin folder (the current folder, by default).
The most important attributes are: The most important attributes are:
* **name**: unique name that senpy will use internally to identify the plugin. * **name**: unique name that senpy will use internally to identify the plugin.
* **module**: indicates the module that contains the plugin code, which will be automatically loaded by senpy. * **module**: indicates the module that contains the plugin code, which will be automatically loaded by senpy.
* **version** * **version**
* extra_params: used to specify parameters that the plugin accepts that are not already part of the senpy API. Those parameters may be required, and have aliased names. For instance: * extra_params: to add parameters to the senpy API when this plugin is requested. Those parameters may be required, and have aliased names. For instance:
.. code:: yaml .. code:: yaml
@@ -68,10 +75,28 @@ The basic methods in a plugin are:
* __init__ * __init__
* activate: used to load memory-hungry resources * activate: used to load memory-hungry resources
* deactivate: used to free up resources * deactivate: used to free up resources
* analyse_entry: called in every user requests. It takes in the parameters supplied by a user and should yield one or more ``Entry`` objects. * analyse_entry: called in every user requests. It takes two parameters: ``Entry``, the entry object, and ``params``, the parameters supplied by the user. It should yield one or more ``Entry`` objects.
Plugins are loaded asynchronously, so don't worry if the activate method takes too long. The plugin will be marked as activated once it is finished executing the method. Plugins are loaded asynchronously, so don't worry if the activate method takes too long. The plugin will be marked as activated once it is finished executing the method.
Entries
=======
Entries are objects that can be annotated.
By default, entries are `NIF contexts <http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core/nif-core.html>`_ represented in JSON-LD format.
Annotations are added to the object like this:
.. code:: python
entry = Entry()
entry.vocabulary__annotationName = 'myvalue'
entry['vocabulary:annotationName'] = 'myvalue'
entry['annotationNameURI'] = 'myvalue'
Where vocabulary is one of the prefixes defined in the default senpy context, and annotationURI is a full URI.
The value may be any valid JSON-LD dictionary.
For simplicity, senpy includes a series of models by default in the ``senpy.models`` module.
Example plugin Example plugin
============== ==============
@@ -117,6 +142,13 @@ Now, in a file named ``helloworld.py``:
F.A.Q. F.A.Q.
====== ======
What annotations can I use?
???????????????????????????
You can add almost any annotation to an entry.
The most common use cases are covered in the :doc:`schema`.
Why does the analyse function yield instead of return? Why does the analyse function yield instead of return?
?????????????????????????????????????????????????????? ??????????????????????????????????????????????????????

11
docs/research.rst Normal file
View File

@@ -0,0 +1,11 @@
Research
--------
If you use Senpy in your research, please cite `Senpy: A Pragmatic Linked Sentiment Analysis Framework <http://gsi.dit.upm.es/index.php/es/investigacion/publicaciones?view=publication&task=show&id=417>`__ (`BibTex <http://gsi.dit.upm.es/index.php/es/investigacion/publicaciones?controller=publications&task=export&format=bibtex&id=417>`__):
.. code-block:: text
Sánchez-Rada, J. F., Iglesias, C. A., Corcuera, I., & Araque, Ó. (2016, October).
Senpy: A Pragmatic Linked Sentiment Analysis Framework.
In Data Science and Advanced Analytics (DSAA),
2016 IEEE International Conference on (pp. 735-742). IEEE.

View File

@@ -1,74 +1,74 @@
Schema Examples Schema
=============== ------
All the examples in this page use the :download:`the main schema <_static/schemas/definitions.json>`. All the examples in this page use the :download:`the main schema <_static/schemas/definitions.json>`.
Simple NIF annotation Simple NIF annotation
--------------------- .....................
Description Description
........... ,,,,,,,,,,,
This example covers the basic example in the NIF documentation: `<http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core/nif-core.html>`_. This example covers the basic example in the NIF documentation: `<http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core/nif-core.html>`_.
Representation Representation
.............. ,,,,,,,,,,,,,,
.. literalinclude:: examples/example-basic.json .. literalinclude:: examples/results/example-basic.json
:language: json-ld :language: json-ld
Sentiment Analysis Sentiment Analysis
--------------------- .....................
Description Description
........... ,,,,,,,,,,,
Representation Representation
.............. ,,,,,,,,,,,,,,
.. literalinclude:: examples/example-sentiment.json .. literalinclude:: examples/results/example-sentiment.json
:emphasize-lines: 5-10,25-33 :emphasize-lines: 5-10,25-33
:language: json-ld :language: json-ld
Suggestion Mining Suggestion Mining
----------------- .................
Description Description
........... ,,,,,,,,,,,
Representation Representation
.............. ,,,,,,,,,,,,,,
.. literalinclude:: examples/example-suggestion.json .. literalinclude:: examples/results/example-suggestion.json
:emphasize-lines: 5-8,22-27 :emphasize-lines: 5-8,22-27
:language: json-ld :language: json-ld
Emotion Analysis Emotion Analysis
---------------- ................
Description Description
........... ,,,,,,,,,,,
Representation Representation
.............. ,,,,,,,,,,,,,,
.. literalinclude:: examples/example-emotion.json .. literalinclude:: examples/results/example-emotion.json
:language: json-ld :language: json-ld
:emphasize-lines: 5-8,25-37 :emphasize-lines: 5-8,25-37
Named Entity Recognition Named Entity Recognition
------------------------ ........................
Description Description
........... ,,,,,,,,,,,
Representation Representation
.............. ,,,,,,,,,,,,,,
.. literalinclude:: examples/example-ner.json .. literalinclude:: examples/results/example-ner.json
:emphasize-lines: 5-8,19-34 :emphasize-lines: 5-8,19-34
:language: json-ld :language: json-ld
Complete example Complete example
---------------- ................
Description Description
........... ,,,,,,,,,,,
This example covers all of the above cases, integrating all the annotations in the same document. This example covers all of the above cases, integrating all the annotations in the same document.
Representation Representation
.............. ,,,,,,,,,,,,,,
.. literalinclude:: examples/example-complete.json .. literalinclude:: examples/results/example-complete.json
:language: json-ld :language: json-ld

View File

@@ -1,35 +1,32 @@
What is Senpy? What is Senpy?
-------------- --------------
Senpy is an open source reference implementation of a linked data model for sentiment and emotion analysis services based on the vocabularies NIF, Marl and Onyx. Senpy is a framework that turns your sentiment or emotion analysis algorithm into a full blown semantic service.
Senpy takes care of:
The overall goal of the reference implementation Senpy is easing the adoption of the proposed linked data model for sentiment and emotion analysis services, so that services from different providers become interoperable. With this aim, the design of the reference implementation has focused on its extensibility and reusability. * Interfacing with the user: parameter validation, error handling.
* Formatting: JSON-LD, Turtle/n-triples input and output, or simple text input
* Linked Data: senpy results are semantically annotated, using a series of well established vocabularies, and sane default URIs.
* User interface: a web UI where users can explore your service and test different settings
* A client to interact with the service. Currently only available in Python.
A modular approach allows organizations to replace individual components with custom ones developed in-house. Furthermore, organizations can benefit from reusing prepackages modules that provide advanced functionalities, such as algorithms for sentiment and emotion analysis, linked data publication or emotion and sentiment mapping between different providers. Sharing your sentiment analysis with the world has never been easier!
Specifications Senpy for service developers
============== ============================
The model used in Senpy is based on the following specifications: Check out the :doc:`plugins` if you have developed an analysis algorithm (e.g. sentiment analysis) and you want to publish it as a service.
* Marl, a vocabulary designed to annotate and describe subjetive opinions expressed on the web or in information systems. Senpy for end users
* Onyx, which is built one the same principles as Marl to annotate and describe emotions, and provides interoperability with Emotion Markup Language. ===================
* NIF 2.0, which defines a semantic format and APO for improving interoperability among natural language processing services
Architecture All services built using senpy share a common interface.
============ This allows users to use them (almost) interchangeably.
Senpy comes with a :ref:`built-in client`.
The main component of a sentiment analysis service is the algorithm itself. However, for the algorithm to work, it needs to get the appropriate parameters from the user, format the results according to the defined API, interact with the user whn errors occur or more information is needed, etc.
Senpy proposes a modular and dynamic architecture that allows: .. toctree::
:caption: Interested? Check out senpy's:
architecture
* Implementing different algorithms in a extensible way, yet offering a common interface.
* Offering common services that facilitate development, so developers can focus on implementing new and better algorithms.
The framework consists of two main modules: Senpy core, which is the building block of the service, and Senpy plugins, which consist of the analysis algorithm. The next figure depicts a simplified version of the processes involved in an analysis with the Senpy framework.
.. image:: senpy-architecture.png
:height: 400px
:width: 800px
:scale: 100 %
:align: center

View File

@@ -1,20 +1,9 @@
Usage Usage
----- -----
The easiest and recommended way is to just use the command-line tool to load your plugins and launch the server. First of all, you need to install the package.
See :doc:`installation` for installation instructions.
.. code:: bash Once installed, the `senpy` command should be available.
senpy
Or, alternatively:
.. code:: bash
python -m senpy
This will create a server with any modules found in the current path.
Useful command-line options Useful command-line options
=========================== ===========================
@@ -23,19 +12,19 @@ In case you want to load modules, which are located in different folders under t
.. code:: bash .. code:: bash
python -m senpy -f . senpy -f .
The default port used by senpy is 5000, but you can change it using the option `--port`. The default port used by senpy is 5000, but you can change it using the `--port` flag.
.. code:: bash .. code:: bash
python -m senpy --port 8080 senpy --port 8080
Also, the host can be changed where senpy is deployed. The default value is `127.0.0.1`. Also, the host can be changed where senpy is deployed. The default value is `127.0.0.1`.
.. code:: bash .. code:: bash
python -m senpy --host 0.0.0.0 senpy --host 0.0.0.0
For more options, see the `--help` page. For more options, see the `--help` page.
@@ -48,15 +37,19 @@ Once the server is launched, there is a basic endpoint in the server, which prov
In case you want to know the different endpoints of the server, there is more information available in the NIF API section_. In case you want to know the different endpoints of the server, there is more information available in the NIF API section_.
CLI CLI demo
=== ========
This video shows how to use senpy through command-line tool. This video shows how to use senpy through command-line tool.
https://asciinema.org/a/9uwef1ghkjk062cw2t4mhzpyk .. image:: https://asciinema.org/a/9uwef1ghkjk062cw2t4mhzpyk.png
:width: 100%
:target: https://asciinema.org/a/9uwef1ghkjk062cw2t4mhzpyk
:alt: CLI demo
Request example in python
========================= Built-in client
===============
This example shows how to make a request to the default plugin: This example shows how to make a request to the default plugin:

8
docs/vocabularies.rst Normal file
View File

@@ -0,0 +1,8 @@
Vocabularies and model
======================
The model used in Senpy is based on the following vocabularies:
* Marl, a vocabulary designed to annotate and describe subjetive opinions expressed on the web or in information systems.
* Onyx, which is built one the same principles as Marl to annotate and describe emotions, and provides interoperability with Emotion Markup Language.
* NIF 2.0, which defines a semantic format and APO for improving interoperability among natural language processing services

View File

@@ -26,7 +26,6 @@ from gevent.wsgi import WSGIServer
from gevent.monkey import patch_all from gevent.monkey import patch_all
import logging import logging
import os import os
import sys
import argparse import argparse
import senpy import senpy
@@ -35,22 +34,6 @@ patch_all(thread=False)
SERVER_PORT = os.environ.get("PORT", 5000) SERVER_PORT = os.environ.get("PORT", 5000)
def info(type, value, tb):
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(type, value, tb)
else:
import traceback
import pdb
# we are NOT in interactive mode, print the exception...
traceback.print_exception(type, value, tb)
print
# ...then start the debugger in post-mortem mode.
# pdb.pm() # deprecated
pdb.post_mortem(tb) # more "modern"
def main(): def main():
parser = argparse.ArgumentParser(description='Run a Senpy server') parser = argparse.ArgumentParser(description='Run a Senpy server')
parser.add_argument( parser.add_argument(
@@ -100,22 +83,25 @@ def main():
rl.setLevel(getattr(logging, args.level)) rl.setLevel(getattr(logging, args.level))
app = Flask(__name__) app = Flask(__name__)
app.debug = args.debug app.debug = args.debug
if args.debug:
sys.excepthook = info
sp = Senpy(app, args.plugins_folder, default_plugins=args.default_plugins) sp = Senpy(app, args.plugins_folder, default_plugins=args.default_plugins)
if args.only_install: if args.only_install:
sp.install_deps() sp.install_deps()
return return
sp.activate_all() sp.activate_all()
http_server = WSGIServer((args.host, args.port), app) print('Senpy version {}'.format(senpy.__version__))
try: print('Server running on port %s:%d. Ctrl+C to quit' % (args.host,
print('Senpy version {}'.format(senpy.__version__)) args.port))
print('Server running on port %s:%d. Ctrl+C to quit' % (args.host, if not app.debug:
args.port)) http_server = WSGIServer((args.host, args.port), app)
http_server.serve_forever() try:
except KeyboardInterrupt: http_server.serve_forever()
print('Bye!') except KeyboardInterrupt:
http_server.stop() print('Bye!')
http_server.stop()
else:
app.run(args.host,
args.port,
debug=True)
sp.deactivate_all() sp.deactivate_all()

View File

@@ -70,7 +70,7 @@ NIF_PARAMS = {
"aliases": ["f", "informat"], "aliases": ["f", "informat"],
"required": False, "required": False,
"default": "text", "default": "text",
"options": ["turtle", "text"], "options": ["turtle", "text", "json-ld"],
}, },
"intype": { "intype": {
"@id": "intype", "@id": "intype",

View File

@@ -25,6 +25,7 @@ from .version import __version__
from functools import wraps from functools import wraps
import logging import logging
import json
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -74,7 +75,7 @@ def basic_api(f):
@wraps(f) @wraps(f)
def decorated_function(*args, **kwargs): def decorated_function(*args, **kwargs):
raw_params = get_params(request) raw_params = get_params(request)
headers = {'X-ORIGINAL-PARAMS': raw_params} headers = {'X-ORIGINAL-PARAMS': json.dumps(raw_params)}
# Get defaults # Get defaults
web_params = parse_params({}, spec=WEB_PARAMS) web_params = parse_params({}, spec=WEB_PARAMS)
api_params = parse_params({}, spec=API_PARAMS) api_params = parse_params({}, spec=API_PARAMS)
@@ -92,6 +93,9 @@ def basic_api(f):
response = f(*args, **kwargs) response = f(*args, **kwargs)
except Error as ex: except Error as ex:
response = ex response = ex
logger.error(ex)
if current_app.debug:
raise
in_headers = web_params['inHeaders'] != "0" in_headers = web_params['inHeaders'] != "0"
expanded = api_params['expanded-jsonld'] expanded = api_params['expanded-jsonld']

View File

@@ -7,7 +7,7 @@ standard_library.install_aliases()
from . import plugins from . import plugins
from .plugins import SenpyPlugin from .plugins import SenpyPlugin
from .models import Error, Entry, Results from .models import Error, Entry, Results, from_string
from .blueprints import api_blueprint, demo_blueprint, ns_blueprint from .blueprints import api_blueprint, demo_blueprint, ns_blueprint
from .api import API_PARAMS, NIF_PARAMS, parse_params from .api import API_PARAMS, NIF_PARAMS, parse_params
@@ -22,11 +22,18 @@ import importlib
import logging import logging
import traceback import traceback
import yaml import yaml
import pip import subprocess
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def log_subprocess_output(process):
for line in iter(process.stdout.readline, b''):
logger.info('%r', line)
for line in iter(process.stderr.readline, b''):
logger.error('%r', line)
class Senpy(object): class Senpy(object):
""" Default Senpy extension for Flask """ """ Default Senpy extension for Flask """
@@ -78,70 +85,101 @@ class Senpy(object):
else: else:
logger.debug("Not a folder: %s", folder) logger.debug("Not a folder: %s", folder)
def _find_plugin(self, params): def _find_plugins(self, params):
api_params = parse_params(params, spec=API_PARAMS) if not self.analysis_plugins:
algo = None
if "algorithm" in api_params and api_params["algorithm"]:
algo = api_params["algorithm"]
elif self.plugins:
algo = self.default_plugin and self.default_plugin.name
if not algo:
raise Error( raise Error(
status=404, status=404,
message=("No plugins found." message=("No plugins found."
" Please install one.").format(algo)) " Please install one."))
if algo not in self.plugins: api_params = parse_params(params, spec=API_PARAMS)
logger.debug(("The algorithm '{}' is not valid\n" algos = None
"Valid algorithms: {}").format(algo, if "algorithm" in api_params and api_params["algorithm"]:
self.plugins.keys())) algos = api_params["algorithm"].split(',')
elif self.default_plugin:
algos = [self.default_plugin.name, ]
else:
raise Error( raise Error(
status=404, status=404,
message="The algorithm '{}' is not valid".format(algo)) message="No default plugin found, and None provided")
if not self.plugins[algo].is_activated: plugins = list()
logger.debug("Plugin not activated: {}".format(algo)) for algo in algos:
raise Error( if algo not in self.plugins:
status=400, logger.debug(("The algorithm '{}' is not valid\n"
message=("The algorithm '{}'" "Valid algorithms: {}").format(algo,
" is not activated yet").format(algo)) self.plugins.keys()))
return self.plugins[algo] raise Error(
status=404,
message="The algorithm '{}' is not valid".format(algo))
def _get_params(self, params, plugin): if not self.plugins[algo].is_activated:
logger.debug("Plugin not activated: {}".format(algo))
raise Error(
status=400,
message=("The algorithm '{}'"
" is not activated yet").format(algo))
plugins.append(self.plugins[algo])
return plugins
def _get_params(self, params, plugin=None):
nif_params = parse_params(params, spec=NIF_PARAMS) nif_params = parse_params(params, spec=NIF_PARAMS)
extra_params = plugin.get('extra_params', {}) if plugin:
specific_params = parse_params(params, spec=extra_params) extra_params = plugin.get('extra_params', {})
nif_params.update(specific_params) specific_params = parse_params(params, spec=extra_params)
nif_params.update(specific_params)
return nif_params return nif_params
def _get_entries(self, params): def _get_entries(self, params):
entry = None
if params['informat'] == 'text': if params['informat'] == 'text':
results = Results()
entry = Entry(text=params['input']) entry = Entry(text=params['input'])
results.entries.append(entry)
elif params['informat'] == 'json-ld':
results = from_string(params['input'], cls=Results)
else: else:
raise NotImplemented('Only text input format implemented') raise NotImplemented('Informat {} is not implemented'.format(params['informat']))
yield entry return results
def _process_entries(self, entries, plugins, nif_params):
if not plugins:
for i in entries:
yield i
return
plugin = plugins[0]
specific_params = self._get_params(nif_params, plugin)
results = plugin.analyse_entries(entries, specific_params)
for i in self._process_entries(results, plugins[1:], nif_params):
yield i
def _process_response(self, resp, plugins, nif_params):
entries = resp.entries
resp.entries = []
for plug in plugins:
resp.analysis.append(plug.id)
for i in self._process_entries(entries, plugins, nif_params):
resp.entries.append(i)
return resp
def analyse(self, **api_params): def analyse(self, **api_params):
"""
Main method that analyses a request, either from CLI or HTTP.
It uses a dictionary of parameters, provided by the user.
"""
logger.debug("analysing with params: {}".format(api_params)) logger.debug("analysing with params: {}".format(api_params))
plugin = self._find_plugin(api_params) plugins = self._find_plugins(api_params)
nif_params = self._get_params(api_params, plugin) nif_params = self._get_params(api_params)
resp = Results() resp = self._get_entries(nif_params)
if 'with_parameters' in api_params: if 'with_parameters' in api_params:
resp.parameters = nif_params resp.parameters = nif_params
try: try:
entries = [] resp = self._process_response(resp, plugins, nif_params)
for i in self._get_entries(nif_params): self.convert_emotions(resp, plugins, nif_params)
entries += list(plugin.analyse_entry(i, nif_params))
resp.entries = entries
self.convert_emotions(resp, plugin, nif_params)
resp.analysis.append(plugin.id)
logger.debug("Returning analysis result: {}".format(resp)) logger.debug("Returning analysis result: {}".format(resp))
except Error as ex: except (Error, Exception) as ex:
logger.exception('Error returning analysis result') if not isinstance(ex, Error):
resp = ex ex = Error(message=str(ex), status=500)
except Exception as ex: logger.error('Error returning analysis result')
logger.exception('Error returning analysis result') raise ex
resp = Error(message=str(ex), status=500)
return resp return resp
def _conversion_candidates(self, fromModel, toModel): def _conversion_candidates(self, fromModel, toModel):
@@ -155,7 +193,7 @@ class Senpy(object):
# logging.debug('Found candidate: {}'.format(candidate)) # logging.debug('Found candidate: {}'.format(candidate))
yield candidate yield candidate
def convert_emotions(self, resp, plugin, params): def convert_emotions(self, resp, plugins, params):
""" """
Conversion of all emotions in a response. Conversion of all emotions in a response.
In addition to converting from one model to another, it has In addition to converting from one model to another, it has
@@ -163,29 +201,35 @@ class Senpy(object):
Needless to say, this is far from an elegant solution, but it works. Needless to say, this is far from an elegant solution, but it works.
@todo refactor and clean up @todo refactor and clean up
""" """
fromModel = plugin.get('onyx:usesEmotionModel', None)
toModel = params.get('emotionModel', None) toModel = params.get('emotionModel', None)
output = params.get('conversion', None)
logger.debug('Asked for model: {}'.format(toModel))
logger.debug('Analysis plugin uses model: {}'.format(fromModel))
if not toModel: if not toModel:
return return
try:
candidate = next(self._conversion_candidates(fromModel, toModel)) logger.debug('Asked for model: {}'.format(toModel))
except StopIteration: output = params.get('conversion', None)
e = Error(('No conversion plugin found for: ' candidates = {}
'{} -> {}'.format(fromModel, toModel))) for plugin in plugins:
e.original_response = resp try:
e.parameters = params fromModel = plugin.get('onyx:usesEmotionModel', None)
raise e candidates[plugin.id] = next(self._conversion_candidates(fromModel, toModel))
logger.debug('Analysis plugin {} uses model: {}'.format(plugin.id, fromModel))
except StopIteration:
e = Error(('No conversion plugin found for: '
'{} -> {}'.format(fromModel, toModel)))
e.original_response = resp
e.parameters = params
raise e
newentries = [] newentries = []
resp.analysis = set(resp.analysis)
for i in resp.entries: for i in resp.entries:
if output == "full": if output == "full":
newemotions = copy.deepcopy(i.emotions) newemotions = copy.deepcopy(i.emotions)
else: else:
newemotions = [] newemotions = []
for j in i.emotions: for j in i.emotions:
plugname = j['prov:wasGeneratedBy']
candidate = candidates[plugname]
resp.analysis.add(candidate.id)
for k in candidate.convert(j, fromModel, toModel, params): for k in candidate.convert(j, fromModel, toModel, params):
k.prov__wasGeneratedBy = candidate.id k.prov__wasGeneratedBy = candidate.id
if output == 'nested': if output == 'nested':
@@ -194,13 +238,13 @@ class Senpy(object):
i.emotions = newemotions i.emotions = newemotions
newentries.append(i) newentries.append(i)
resp.entries = newentries resp.entries = newentries
resp.analysis.append(candidate.id)
@property @property
def default_plugin(self): def default_plugin(self):
candidate = self._default candidate = self._default
if not candidate: if not candidate:
candidates = self.filter_plugins(is_activated=True) candidates = self.filter_plugins(plugin_type='analysisPlugin',
is_activated=True)
if len(candidates) > 0: if len(candidates) > 0:
candidate = list(candidates.values())[0] candidate = list(candidates.values())[0]
logger.debug("Default: {}".format(candidate)) logger.debug("Default: {}".format(candidate))
@@ -296,13 +340,19 @@ class Senpy(object):
def _install_deps(cls, info=None): def _install_deps(cls, info=None):
requirements = info.get('requirements', []) requirements = info.get('requirements', [])
if requirements: if requirements:
pip_args = [] pip_args = ['pip']
pip_args.append('install') pip_args.append('install')
pip_args.append('--use-wheel') pip_args.append('--use-wheel')
for req in requirements: for req in requirements:
pip_args.append(req) pip_args.append(req)
logger.info('Installing requirements: ' + str(requirements)) logger.info('Installing requirements: ' + str(requirements))
pip.main(pip_args) process = subprocess.Popen(pip_args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
log_subprocess_output(process)
exitcode = process.wait()
if exitcode != 0:
raise Error("Dependencies not properly installed")
@classmethod @classmethod
def _load_module(cls, name, root): def _load_module(cls, name, root):

View File

@@ -214,6 +214,7 @@ class BaseModel(SenpyMixin, dict):
temp['@type'] = getattr(self, '@type') temp['@type'] = getattr(self, '@type')
except AttributeError: except AttributeError:
logger.warn('Creating an instance of an unknown model') logger.warn('Creating an instance of an unknown model')
super(BaseModel, self).__init__(temp) super(BaseModel, self).__init__(temp)
def _get_key(self, key): def _get_key(self, key):
@@ -252,13 +253,32 @@ def register(rsubclass, rtype=None):
_subtypes[rtype or rsubclass.__name__] = rsubclass _subtypes[rtype or rsubclass.__name__] = rsubclass
def from_dict(indict): def from_dict(indict, cls=None):
target = indict.get('@type', None) if not cls:
if target and target in _subtypes: target = indict.get('@type', None)
cls = _subtypes[target] try:
else: if target and target in _subtypes:
cls = BaseModel cls = _subtypes[target]
return cls(**indict) else:
cls = BaseModel
except Exception:
cls = BaseModel
outdict = dict()
for k, v in indict.items():
if k == '@context':
pass
elif isinstance(v, dict):
v = from_dict(indict[k])
elif isinstance(v, list):
for ix, v2 in enumerate(v):
if isinstance(v2, dict):
v[ix] = from_dict(v2)
outdict[k] = v
return cls(**outdict)
def from_string(string, **kwargs):
return from_dict(json.loads(string), **kwargs)
def from_json(injson): def from_json(injson):
@@ -308,7 +328,7 @@ for i in [
_ErrorModel = from_schema('error') _ErrorModel = from_schema('error')
class Error(SenpyMixin, BaseException): class Error(SenpyMixin, Exception):
def __init__(self, message, *args, **kwargs): def __init__(self, message, *args, **kwargs):
super(Error, self).__init__(self, message, message) super(Error, self).__init__(self, message, message)
self._error = _ErrorModel(message=message, *args, **kwargs) self._error = _ErrorModel(message=message, *args, **kwargs)
@@ -337,5 +357,8 @@ class Error(SenpyMixin, BaseException):
def __delattr__(self, key): def __delattr__(self, key):
delattr(self._error, key) delattr(self._error, key)
def __str__(self):
return str(self.to_JSON(with_context=False))
register(Error, 'error') register(Error, 'error')

View File

@@ -13,7 +13,7 @@ from .. import models
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class SenpyPlugin(models.Plugin): class Plugin(models.Plugin):
def __init__(self, info=None): def __init__(self, info=None):
""" """
Provides a canonical name for plugins and serves as base for other Provides a canonical name for plugins and serves as base for other
@@ -24,7 +24,7 @@ class SenpyPlugin(models.Plugin):
"information for the plugin.")) "information for the plugin."))
logger.debug("Initialising {}".format(info)) logger.debug("Initialising {}".format(info))
id = 'plugins/{}_{}'.format(info['name'], info['version']) id = 'plugins/{}_{}'.format(info['name'], info['version'])
super(SenpyPlugin, self).__init__(id=id, **info) super(Plugin, self).__init__(id=id, **info)
self.is_activated = False self.is_activated = False
def get_folder(self): def get_folder(self):
@@ -37,7 +37,10 @@ class SenpyPlugin(models.Plugin):
pass pass
class AnalysisPlugin(SenpyPlugin): SenpyPlugin = Plugin
class AnalysisPlugin(Plugin):
def analyse(self, *args, **kwargs): def analyse(self, *args, **kwargs):
raise NotImplemented( raise NotImplemented(
@@ -57,8 +60,14 @@ class AnalysisPlugin(SenpyPlugin):
for i in results.entries: for i in results.entries:
yield i yield i
def analyse_entries(self, entries, parameters):
for entry in entries:
logger.debug('Analysing entry with plugin {}: {}'.format(self, entry))
for result in self.analyse_entry(entry, parameters):
yield result
class ConversionPlugin(SenpyPlugin):
class ConversionPlugin(Plugin):
pass pass

View File

@@ -6,6 +6,33 @@ logger = logging.getLogger(__name__)
class CentroidConversion(EmotionConversionPlugin): class CentroidConversion(EmotionConversionPlugin):
def __init__(self, info):
if 'centroids' not in info:
raise Error('Centroid conversion plugins should provide '
'the centroids in their senpy file')
if 'onyx:doesConversion' not in info:
if 'centroids_direction' not in info:
raise Error('Please, provide centroids direction')
cf, ct = info['centroids_direction']
info['onyx:doesConversion'] = [{
'onyx:conversionFrom': cf,
'onyx:conversionTo': ct
}, {
'onyx:conversionFrom': ct,
'onyx:conversionTo': cf
}]
if 'aliases' in info:
aliases = info['aliases']
ncentroids = {}
for k1, v1 in info['centroids'].items():
nv1 = {}
for k2, v2 in v1.items():
nv1[aliases.get(k2, k2)] = v2
ncentroids[aliases.get(k1, k1)] = nv1
info['centroids'] = ncentroids
super(CentroidConversion, self).__init__(info)
def _forward_conversion(self, original): def _forward_conversion(self, original):
"""Sum the VAD value of all categories found.""" """Sum the VAD value of all categories found."""
@@ -25,7 +52,7 @@ class CentroidConversion(EmotionConversionPlugin):
dimensions = list(self.centroids.values())[0] dimensions = list(self.centroids.values())[0]
def distance(e1, e2): def distance(e1, e2):
return sum((e1[k] - e2.get(self.aliases[k], 0)) for k in dimensions) return sum((e1[k] - e2.get(k, 0)) for k in dimensions)
emotion = '' emotion = ''
mindistance = 10000000000000000000000.0 mindistance = 10000000000000000000000.0
@@ -40,11 +67,12 @@ class CentroidConversion(EmotionConversionPlugin):
def convert(self, emotionSet, fromModel, toModel, params): def convert(self, emotionSet, fromModel, toModel, params):
cf, ct = self.centroids_direction cf, ct = self.centroids_direction
logger.debug('{}\n{}\n{}\n{}'.format(emotionSet, fromModel, toModel, params)) logger.debug(
'{}\n{}\n{}\n{}'.format(emotionSet, fromModel, toModel, params))
e = EmotionSet() e = EmotionSet()
if fromModel == cf: if fromModel == cf and toModel == ct:
e.onyx__hasEmotion.append(self._forward_conversion(emotionSet)) e.onyx__hasEmotion.append(self._forward_conversion(emotionSet))
elif fromModel == ct: elif fromModel == ct and toModel == cf:
for i in emotionSet.onyx__hasEmotion: for i in emotionSet.onyx__hasEmotion:
e.onyx__hasEmotion.append(self._backwards_conversion(i)) e.onyx__hasEmotion.append(self._backwards_conversion(i))
else: else:

View File

@@ -0,0 +1,39 @@
---
name: Ekman2FSRE
module: senpy.plugins.conversion.centroids
description: Plugin to convert emotion sets from Ekman to VAD
version: 0.1
# No need to specify onyx:doesConversion because centroids.py adds it automatically from centroids_direction
centroids:
anger:
A: 6.95
D: 5.1
V: 2.7
disgust:
A: 5.3
D: 8.05
V: 2.7
fear:
A: 6.5
D: 3.6
V: 3.2
happiness:
A: 7.22
D: 6.28
V: 8.6
sadness:
A: 5.21
D: 2.82
V: 2.21
centroids_direction:
- emoml:big6
- emoml:fsre-dimensions
aliases: # These are aliases for any key in the centroid, to avoid repeating a long name several times
A: emoml:arousal
V: emoml:valence
D: emoml:dominance
anger: emoml:big6anger
disgust: emoml:big6disgust
fear: emoml:big6fear
happiness: emoml:big6happiness
sadness: emoml:big6sadness

View File

@@ -1,38 +1,39 @@
--- ---
name: Ekman2VAD name: Ekman2PAD
module: senpy.plugins.conversion.centroids module: senpy.plugins.conversion.centroids
description: Plugin to convert emotion sets from Ekman to VAD description: Plugin to convert emotion sets from Ekman to VAD
version: 0.1 version: 0.1
onyx:doesConversion: # No need to specify onyx:doesConversion because centroids.py adds it automatically from centroids_direction
- onyx:conversionFrom: emoml:big6
onyx:conversionTo: emoml:fsre-dimensions
- onyx:conversionFrom: emoml:fsre-dimensions
onyx:conversionTo: emoml:big6
centroids: centroids:
emoml:big6anger: anger:
A: 6.95 A: 6.95
D: 5.1 D: 5.1
V: 2.7 V: 2.7
emoml:big6disgust: disgust:
A: 5.3 A: 5.3
D: 8.05 D: 8.05
V: 2.7 V: 2.7
emoml:big6fear: fear:
A: 6.5 A: 6.5
D: 3.6 D: 3.6
V: 3.2 V: 3.2
emoml:big6happiness: happiness:
A: 7.22 A: 7.22
D: 6.28 D: 6.28
V: 8.6 V: 8.6
emoml:big6sadness: sadness:
A: 5.21 A: 5.21
D: 2.82 D: 2.82
V: 2.21 V: 2.21
centroids_direction: centroids_direction:
- emoml:big6 - emoml:big6
- emoml:fsre-dimensions - emoml:pad
aliases: aliases: # These are aliases for any key in the centroid, to avoid repeating a long name several times
A: emoml:arousal A: emoml:arousal
V: emoml:valence V: emoml:valence
D: emoml:dominance D: emoml:dominance
anger: emoml:big6anger
disgust: emoml:big6disgust
fear: emoml:big6fear
happiness: emoml:big6happiness
sadness: emoml:big6sadness

View File

@@ -37,6 +37,12 @@
"@type": "@id", "@type": "@id",
"@container": "@set" "@container": "@set"
}, },
"plugins": {
"@container": "@list"
},
"options": {
"@container": "@set"
},
"prov:wasGeneratedBy": { "prov:wasGeneratedBy": {
"@type": "@id" "@type": "@id"
}, },

View File

@@ -6,6 +6,7 @@
"properties": { "properties": {
"plugins": { "plugins": {
"type": "array", "type": "array",
"default": [],
"items": { "items": {
"$ref": "plugin.json" "$ref": "plugin.json"
} }

View File

@@ -47,7 +47,7 @@
This website is the senpy Playground, which allows you to test the instance of senpy in this server. It provides a user-friendly interface to the functions exposed by the senpy API. This website is the senpy Playground, which allows you to test the instance of senpy in this server. It provides a user-friendly interface to the functions exposed by the senpy API.
</p> </p>
<p> <p>
Once you get comfortable with the parameters and results, you are encouraged to issue your own requests to the API endpoint, which should be <a href="/api">here</a>. Once you get comfortable with the parameters and results, you are encouraged to issue your own requests to the API endpoint. You can find examples of API URL's when you try out a plugin with the "Analyse!" button on the "Test it" tab.
</p> </p>
<p> <p>
These are some of the things you can do with the API: These are some of the things you can do with the API:

View File

@@ -4,4 +4,5 @@ from senpy.plugins import SentimentPlugin
class DummyPlugin(SentimentPlugin): class DummyPlugin(SentimentPlugin):
def analyse_entry(self, entry, params): def analyse_entry(self, entry, params):
entry.text = entry.text[::-1] entry.text = entry.text[::-1]
entry.reversed = entry.get('reversed', 0) + 1
yield entry yield entry

View File

@@ -1,8 +1,8 @@
from senpy.plugins import SenpyPlugin from senpy.plugins import AnalysisPlugin
from time import sleep from time import sleep
class SleepPlugin(SenpyPlugin): class SleepPlugin(AnalysisPlugin):
def activate(self, *args, **kwargs): def activate(self, *args, **kwargs):
sleep(self.timeout) sleep(self.timeout)

View File

@@ -19,6 +19,7 @@ def parse_resp(resp):
class BlueprintsTest(TestCase): class BlueprintsTest(TestCase):
def setUp(self): def setUp(self):
self.app = Flask("test_extensions") self.app = Flask("test_extensions")
self.app.debug = False
self.client = self.app.test_client() self.client = self.app.test_client()
self.senpy = Senpy() self.senpy = Senpy()
self.senpy.init_app(self.app) self.senpy.init_app(self.app)

View File

@@ -10,7 +10,7 @@ except ImportError:
from functools import partial from functools import partial
from senpy.extensions import Senpy from senpy.extensions import Senpy
from senpy.models import Error, Results, Entry, EmotionSet, Emotion from senpy.models import Error, Results, Entry, EmotionSet, Emotion, Plugin
from flask import Flask from flask import Flask
from unittest import TestCase from unittest import TestCase
@@ -61,6 +61,19 @@ class ExtensionsTest(TestCase):
assert len(self.senpy.plugins) >= 3 assert len(self.senpy.plugins) >= 3
assert self.senpy.plugins["Sleep"].is_activated assert self.senpy.plugins["Sleep"].is_activated
def test_installing_nonexistent(self):
""" Fail if the dependencies cannot be met """
info = {
'name': 'TestPipFail',
'module': 'dummy',
'description': None,
'requirements': ['IAmMakingThisPackageNameUpToFail'],
'version': 0
}
root = os.path.join(self.dir, 'plugins', 'dummy_plugin')
with self.assertRaises(Error):
name, module = self.senpy._load_plugin_from_info(info, root=root)
def test_disabling(self): def test_disabling(self):
""" Disabling a plugin """ """ Disabling a plugin """
self.senpy.deactivate_all(sync=True) self.senpy.deactivate_all(sync=True)
@@ -96,19 +109,49 @@ class ExtensionsTest(TestCase):
assert r2.analysis[0] == "plugins/Dummy_0.1" assert r2.analysis[0] == "plugins/Dummy_0.1"
assert r1.entries[0].text == 'input' assert r1.entries[0].text == 'input'
def test_analyse_jsonld(self):
""" Using a plugin with JSON-LD input"""
js_input = '''{
"@id": "prueba",
"@type": "results",
"entries": [
{"@id": "entry1",
"text": "tupni",
"@type": "entry"
}
]
}'''
r1 = self.senpy.analyse(algorithm="Dummy",
input=js_input,
informat="json-ld",
output="tuptuo")
r2 = self.senpy.analyse(input="tupni", output="tuptuo")
assert r1.analysis[0] == "plugins/Dummy_0.1"
assert r2.analysis[0] == "plugins/Dummy_0.1"
assert r1.entries[0].text == 'input'
def test_analyse_error(self): def test_analyse_error(self):
mm = mock.MagicMock() mm = mock.MagicMock()
mm.analyse_entry.side_effect = Error('error on analysis', status=900) mm.id = 'magic_mock'
mm.analyse_entries.side_effect = Error('error on analysis', status=500)
self.senpy.plugins['MOCK'] = mm self.senpy.plugins['MOCK'] = mm
resp = self.senpy.analyse(input='nothing', algorithm='MOCK') try:
assert resp['message'] == 'error on analysis' self.senpy.analyse(input='nothing', algorithm='MOCK')
assert resp['status'] == 900 assert False
except Error as ex:
assert ex['message'] == 'error on analysis'
assert ex['status'] == 500
mm.analyse.side_effect = Exception('generic exception on analysis') mm.analyse.side_effect = Exception('generic exception on analysis')
mm.analyse_entry.side_effect = Exception( mm.analyse_entries.side_effect = Exception(
'generic exception on analysis') 'generic exception on analysis')
resp = self.senpy.analyse(input='nothing', algorithm='MOCK')
assert resp['message'] == 'generic exception on analysis' try:
assert resp['status'] == 500 self.senpy.analyse(input='nothing', algorithm='MOCK')
assert False
except Error as ex:
assert ex['message'] == 'generic exception on analysis'
assert ex['status'] == 500
def test_filtering(self): def test_filtering(self):
""" Filtering plugins """ """ Filtering plugins """
@@ -125,11 +168,12 @@ class ExtensionsTest(TestCase):
def test_convert_emotions(self): def test_convert_emotions(self):
self.senpy.activate_all() self.senpy.activate_all()
plugin = { plugin = Plugin({
'id': 'imaginary', 'id': 'imaginary',
'onyx:usesEmotionModel': 'emoml:fsre-dimensions' 'onyx:usesEmotionModel': 'emoml:fsre-dimensions'
} })
eSet1 = EmotionSet() eSet1 = EmotionSet()
eSet1.prov__wasGeneratedBy = plugin['id']
eSet1['onyx:hasEmotion'].append(Emotion({ eSet1['onyx:hasEmotion'].append(Emotion({
'emoml:arousal': 1, 'emoml:arousal': 1,
'emoml:potency': 0, 'emoml:potency': 0,
@@ -145,19 +189,19 @@ class ExtensionsTest(TestCase):
'conversion': 'full'} 'conversion': 'full'}
r1 = deepcopy(response) r1 = deepcopy(response)
self.senpy.convert_emotions(r1, self.senpy.convert_emotions(r1,
plugin, [plugin, ],
params) params)
assert len(r1.entries[0].emotions) == 2 assert len(r1.entries[0].emotions) == 2
params['conversion'] = 'nested' params['conversion'] = 'nested'
r2 = deepcopy(response) r2 = deepcopy(response)
self.senpy.convert_emotions(r2, self.senpy.convert_emotions(r2,
plugin, [plugin, ],
params) params)
assert len(r2.entries[0].emotions) == 1 assert len(r2.entries[0].emotions) == 1
assert r2.entries[0].emotions[0]['prov:wasDerivedFrom'] == eSet1 assert r2.entries[0].emotions[0]['prov:wasDerivedFrom'] == eSet1
params['conversion'] = 'filtered' params['conversion'] = 'filtered'
r3 = deepcopy(response) r3 = deepcopy(response)
self.senpy.convert_emotions(r3, self.senpy.convert_emotions(r3,
plugin, [plugin, ],
params) params)
assert len(r3.entries[0].emotions) == 1 assert len(r3.entries[0].emotions) == 1

View File

@@ -11,8 +11,12 @@ from senpy.models import (Emotion,
Entry, Entry,
Error, Error,
Results, Results,
Sentiment) Sentiment,
from senpy.plugins import SenpyPlugin Plugins,
Plugin,
from_string,
from_dict)
from senpy import plugins
from pprint import pprint from pprint import pprint
@@ -53,8 +57,8 @@ class ModelsTest(TestCase):
assert (received["entries"][0]["nif:isString"] != "Not testing") assert (received["entries"][0]["nif:isString"] != "Not testing")
def test_id(self): def test_id(self):
''' Adding the id after creation should overwrite the automatic ID """ Adding the id after creation should overwrite the automatic ID
''' """
r = Entry() r = Entry()
j = r.jsonld() j = r.jsonld()
assert '@id' in j assert '@id' in j
@@ -94,8 +98,16 @@ class ModelsTest(TestCase):
r.validate() r.validate()
def test_plugins(self): def test_plugins(self):
self.assertRaises(Error, SenpyPlugin) self.assertRaises(Error, plugins.Plugin)
p = SenpyPlugin({"name": "dummy", "version": 0}) p = plugins.Plugin({"name": "dummy",
"version": 0,
"extra_params": {
"none": {
"options": ["es", ],
"required": False,
"default": "0"
}
}})
c = p.jsonld() c = p.jsonld()
assert "info" not in c assert "info" not in c
assert "repo" not in c assert "repo" not in c
@@ -103,11 +115,13 @@ class ModelsTest(TestCase):
logging.debug("Framed:") logging.debug("Framed:")
logging.debug(c) logging.debug(c)
p.validate() p.validate()
assert "es" in c['extra_params']['none']['options']
assert isinstance(c['extra_params']['none']['options'], list)
def test_str(self): def test_str(self):
"""The string representation shouldn't include private variables""" """The string representation shouldn't include private variables"""
r = Results() r = Results()
p = SenpyPlugin({"name": "STR test", "version": 0}) p = plugins.Plugin({"name": "STR test", "version": 0})
p._testing = 0 p._testing = 0
s = str(p) s = str(p)
assert "_testing" not in s assert "_testing" not in s
@@ -143,3 +157,34 @@ class ModelsTest(TestCase):
print(t) print(t)
g = rdflib.Graph().parse(data=t, format='turtle') g = rdflib.Graph().parse(data=t, format='turtle')
assert len(g) == len(triples) assert len(g) == len(triples)
def test_single_plugin(self):
"""A response with a single plugin should still return a list"""
plugs = Plugins()
for i in range(10):
p = Plugin({'id': str(i),
'version': 0,
'description': 'dummy'})
plugs.plugins.append(p)
assert isinstance(plugs.plugins, list)
js = plugs.jsonld()
assert isinstance(js['plugins'], list)
def test_from_string(self):
results = {
'@type': 'results',
'@id': 'prueba',
'entries': [{
'@id': 'entry1',
'@type': 'entry',
'text': 'TEST'
}]
}
recovered = from_dict(results)
assert isinstance(recovered, Results)
assert isinstance(recovered.entries[0], Entry)
string = json.dumps(results)
recovered = from_string(string)
assert isinstance(recovered, Results)
assert isinstance(recovered.entries[0], Entry)