1
0
mirror of https://github.com/gsi-upm/senpy synced 2024-11-22 08:12:27 +00:00

Module script and improvement in JSON-LD

This commit is contained in:
J. Fernando Sánchez 2014-12-02 13:31:15 +01:00
parent ff14925056
commit 37a098109f
6 changed files with 92 additions and 25 deletions

6
app.py
View File

@ -15,9 +15,9 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # 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() from gevent.monkey import patch_all; patch_all()
import gevent import gevent
@ -39,5 +39,5 @@ if __name__ == '__main__':
import logging import logging
logging.basicConfig(level=config.DEBUG) logging.basicConfig(level=config.DEBUG)
app.debug = config.DEBUG app.debug = config.DEBUG
http_server = WSGIServer(('', 5000), app) http_server = WSGIServer(('', config.SERVER_PORT), app)
http_server.serve_forever() http_server.serve_forever()

View File

@ -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_value = int(res.json()["data"][0]["polarity"]) * 25
polarity = "marl:Neutral" polarity = "marl:Neutral"
if polarity_value > 50: if polarity_value > 50:
polarity = "marl:Positive" polarity = "marl:Positive"
elif polarity_value < 50: elif polarity_value < 50:
polarity = "marl:Negative" polarity = "marl:Negative"
entry = Entry(text=params["input"], entry = Entry(id="Entry0", text=params["input"])
prefix=params.get("prefix", "")) opinion = Opinion(id="Opinion0",
opinion = Opinion(hasPolarity=polarity, hasPolarity=polarity,
polarityValue=polarity_value, polarityValue=polarity_value)
prefix=params.get("prefix", ""))
opinion["prov:wasGeneratedBy"] = self.id opinion["prov:wasGeneratedBy"] = self.id
entry.opinions.append(opinion) entry.opinions.append(opinion)
entry.language = lang entry.language = lang

View File

@ -21,5 +21,3 @@ Sentiment analysis server in Python
import extensions import extensions
import blueprints import blueprints
import plugins import plugins
__version__ = "0.2.8"

View File

@ -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 flask import Flask
from extensions import Senpy 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 = Flask(__name__)
sp = Senpy() app.debug = args.debug
sp.init_app(app) sp = Senpy(app, args.plugins_folder)
app.debug = True sp.activate_all()
app.run() 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!"

View File

@ -6,10 +6,12 @@ from collections import defaultdict
class Leaf(defaultdict): class Leaf(defaultdict):
_prefix = None _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) super(Leaf, self).__init__(ofclass)
if context: if context:
self.context = context self.context = context
if id:
self.id = id
self._prefix = prefix self._prefix = prefix
def __getattr__(self, key): def __getattr__(self, key):
@ -31,8 +33,8 @@ class Leaf(defaultdict):
return super(Leaf, self).__delitem__(self._get_key(key)) return super(Leaf, self).__delitem__(self._get_key(key))
def _get_key(self, key): def _get_key(self, key):
if key is "context": if key in ["context", "id"]:
return "@context" return "@{}".format(key)
elif self._prefix: elif self._prefix:
return "{}:{}".format(self._prefix, key) return "{}:{}".format(self._prefix, key)
else: else:
@ -56,11 +58,13 @@ class Leaf(defaultdict):
class Response(Leaf): class Response(Leaf):
def __init__(self, context=None, *args, **kwargs): def __init__(self, context=None, base=None, *args, **kwargs):
if context is None: if context is None:
context = "{}/context.jsonld".format(os.path.dirname( context = "{}/context.jsonld".format(os.path.dirname(
os.path.realpath(__file__))) os.path.realpath(__file__)))
super(Response, self).__init__(*args, context=context, **kwargs) super(Response, self).__init__(*args, context=context, **kwargs)
if base:
self.context["@base"] = base
self["analysis"] = [] self["analysis"] = []
self["entries"] = [] self["entries"] = []
@ -77,9 +81,9 @@ class Entry(Leaf):
class Opinion(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): def __init__(self, polarityValue=None, hasPolarity=None, *args, **kwargs):
super(Opinion, self).__init__(context=self.opinionContext, super(Opinion, self).__init__( prefix="marl",
*args, *args,
**kwargs) **kwargs)
if polarityValue is not None: if polarityValue is not None:

View File

@ -8,7 +8,7 @@ install_reqs = parse_requirements("requirements.txt")
# e.g. ['django==1.5.1', 'mezzanine==1.4.6'] # e.g. ['django==1.5.1', 'mezzanine==1.4.6']
reqs = [str(ir.req) for ir in install_reqs] reqs = [str(ir.req) for ir in install_reqs]
VERSION = "0.3.0" VERSION = "0.3.1"
print(reqs) print(reqs)