From 37a098109f98fd72a922f95fa45e7a4b3c85ff27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=2E=20Fernando=20S=C3=A1nchez?= Date: Tue, 2 Dec 2014 13:31:15 +0100 Subject: [PATCH] Module script and improvement in JSON-LD --- app.py | 8 +-- plugins/sentiment140/sentiment140.py | 11 ++-- senpy/__init__.py | 2 - senpy/__main__.py | 78 +++++++++++++++++++++++++--- senpy/models.py | 16 +++--- setup.py | 2 +- 6 files changed, 92 insertions(+), 25 deletions(-) diff --git a/app.py b/app.py index c11dd63..92c596a 100644 --- a/app.py +++ b/app.py @@ -15,9 +15,9 @@ # See the License for the specific language governing permissions and # limitations under the License. """ -Simple Sentiment Analysis server for EUROSENTIMENT +This is a helper for development. If you want to run Senpy use: -This class shows how to use the nif_server module to create custom services. + python -m senpy """ from gevent.monkey import patch_all; patch_all() import gevent @@ -39,5 +39,5 @@ if __name__ == '__main__': import logging logging.basicConfig(level=config.DEBUG) app.debug = config.DEBUG - http_server = WSGIServer(('', 5000), app) - http_server.serve_forever() \ No newline at end of file + http_server = WSGIServer(('', config.SERVER_PORT), app) + http_server.serve_forever() diff --git a/plugins/sentiment140/sentiment140.py b/plugins/sentiment140/sentiment140.py index fa02c9d..6977eb1 100644 --- a/plugins/sentiment140/sentiment140.py +++ b/plugins/sentiment140/sentiment140.py @@ -15,18 +15,17 @@ class Sentiment140Plugin(SentimentPlugin): ) ) - response = Response() + response = Response(base=params.get("prefix", None)) polarity_value = int(res.json()["data"][0]["polarity"]) * 25 polarity = "marl:Neutral" if polarity_value > 50: polarity = "marl:Positive" elif polarity_value < 50: polarity = "marl:Negative" - entry = Entry(text=params["input"], - prefix=params.get("prefix", "")) - opinion = Opinion(hasPolarity=polarity, - polarityValue=polarity_value, - prefix=params.get("prefix", "")) + entry = Entry(id="Entry0", text=params["input"]) + opinion = Opinion(id="Opinion0", + hasPolarity=polarity, + polarityValue=polarity_value) opinion["prov:wasGeneratedBy"] = self.id entry.opinions.append(opinion) entry.language = lang diff --git a/senpy/__init__.py b/senpy/__init__.py index 1283b48..ca7dcf1 100644 --- a/senpy/__init__.py +++ b/senpy/__init__.py @@ -21,5 +21,3 @@ Sentiment analysis server in Python import extensions import blueprints import plugins - -__version__ = "0.2.8" diff --git a/senpy/__main__.py b/senpy/__main__.py index f5db480..d3b3fb9 100644 --- a/senpy/__main__.py +++ b/senpy/__main__.py @@ -1,7 +1,73 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# Copyright 2014 J. Fernando Sánchez Rada - Grupo de Sistemas Inteligentes +# DIT, UPM +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Senpy is a modular sentiment analysis server. This script runs an instance of +the server. + +""" +from gevent.monkey import patch_all; patch_all(thread=False) +import gevent from flask import Flask -from extensions import Senpy -app = Flask(__name__) -sp = Senpy() -sp.init_app(app) -app.debug = True -app.run() +from senpy.extensions import Senpy +import logging +import os +from gevent.wsgi import WSGIServer +import argparse + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Run a Senpy server') + parser.add_argument('--level', + "-l", + metavar="logging_level", + type=str, + default="INFO", + help='Logging level') + parser.add_argument('--debug', + "-d", + metavar="debug", + type=bool, + default=False, + help='Run the application in debug mode') + parser.add_argument('--host', + type=str, + default = "127.0.0.1", + help='Use 0.0.0.0 to accept requests from any host.') + parser.add_argument('--port', + '-p', + type=int, + default = 5000, + help='Port to listen on.') + parser.add_argument('--plugins-folder', + '-f', + type=str, + default = "plugins", + help='Where to look for plugins.') + args = parser.parse_args() + logging.basicConfig(level=getattr(logging,args.level)) + app = Flask(__name__) + app.debug = args.debug + sp = Senpy(app, args.plugins_folder) + sp.activate_all() + import logging + http_server = WSGIServer((args.host, args.port), app) + try: + print "Server running on port %s:%d. Ctrl+C to quit" % (args.host, + args.port) + http_server.serve_forever() + except KeyboardInterrupt: + http_server.stop() + print "Bye!" diff --git a/senpy/models.py b/senpy/models.py index 8b51cf9..e210c84 100644 --- a/senpy/models.py +++ b/senpy/models.py @@ -6,10 +6,12 @@ from collections import defaultdict class Leaf(defaultdict): _prefix = None - def __init__(self, context=None, prefix=None, ofclass=list): + def __init__(self, id=None, context=None, prefix=None, ofclass=list): super(Leaf, self).__init__(ofclass) if context: self.context = context + if id: + self.id = id self._prefix = prefix def __getattr__(self, key): @@ -31,8 +33,8 @@ class Leaf(defaultdict): return super(Leaf, self).__delitem__(self._get_key(key)) def _get_key(self, key): - if key is "context": - return "@context" + if key in ["context", "id"]: + return "@{}".format(key) elif self._prefix: return "{}:{}".format(self._prefix, key) else: @@ -56,11 +58,13 @@ class Leaf(defaultdict): class Response(Leaf): - def __init__(self, context=None, *args, **kwargs): + def __init__(self, context=None, base=None, *args, **kwargs): if context is None: context = "{}/context.jsonld".format(os.path.dirname( os.path.realpath(__file__))) super(Response, self).__init__(*args, context=context, **kwargs) + if base: + self.context["@base"] = base self["analysis"] = [] self["entries"] = [] @@ -77,9 +81,9 @@ class Entry(Leaf): class Opinion(Leaf): - opinionContext = {"@vocab": "http://www.gsi.dit.upm.es/ontologies/marl/ns#"} + #opinionContext = {"@vocab": "http://www.gsi.dit.upm.es/ontologies/marl/ns#"} def __init__(self, polarityValue=None, hasPolarity=None, *args, **kwargs): - super(Opinion, self).__init__(context=self.opinionContext, + super(Opinion, self).__init__( prefix="marl", *args, **kwargs) if polarityValue is not None: diff --git a/setup.py b/setup.py index b4352fa..29f1f8d 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ install_reqs = parse_requirements("requirements.txt") # e.g. ['django==1.5.1', 'mezzanine==1.4.6'] reqs = [str(ir.req) for ir in install_reqs] -VERSION = "0.3.0" +VERSION = "0.3.1" print(reqs)