1
0
mirror of https://github.com/gsi-upm/senpy synced 2024-11-21 15:52:28 +00:00

Closer to py3

This commit is contained in:
J. Fernando Sánchez 2015-12-17 19:47:11 +01:00
parent ecc2a8312a
commit a79df7a3da
5 changed files with 36 additions and 171 deletions

View File

@ -55,7 +55,7 @@ def get_params(req, params=BASIC_PARAMS):
elif req.method == 'GET': elif req.method == 'GET':
indict = req.args indict = req.args
else: else:
raise ValueError("Invalid data") raise Error(message="Invalid data")
outdict = {} outdict = {}
wrong_params = {} wrong_params = {}
@ -82,7 +82,7 @@ def get_params(req, params=BASIC_PARAMS):
"errors": {param: error for param, error in "errors": {param: error for param, error in
iteritems(wrong_params)} iteritems(wrong_params)}
}) })
raise ValueError(message) raise Error(message=message)
return outdict return outdict
@ -124,7 +124,7 @@ def api():
response = current_app.senpy.analyse(**params) response = current_app.senpy.analyse(**params)
in_headers = params["inHeaders"] != "0" in_headers = params["inHeaders"] != "0"
return response.flask(in_headers=in_headers) return response.flask(in_headers=in_headers)
except ValueError as ex: except Error as ex:
return ex.message.flask() return ex.message.flask()

View File

@ -1,90 +1,22 @@
from __future__ import print_function
from six import string_types
import json import json
import os import os
import logging import logging
from builtins import str
from collections import defaultdict from collections import defaultdict
from pyld import jsonld from pyld import jsonld
from flask import Response as FlaskResponse from flask import Response as FlaskResponse
class Leaf(dict): class Response(object):
_prefix = None
_frame = {}
_context = {}
def __init__(self, @property
*args, def context(self):
**kwargs): if not hasattr(self, '_context'):
self._context = None
id = kwargs.pop("id", None) return self._context
context = kwargs.pop("context", self._context)
vocab = kwargs.pop("vocab", None)
prefix = kwargs.pop("prefix", None)
frame = kwargs.pop("frame", None)
super(Leaf, self).__init__(*args, **kwargs)
if context is not None:
self.context = context
if frame is not None:
self._frame = frame
self._prefix = prefix
self.id = id
def __getattr__(self, key):
try:
return object.__getattr__(self, key)
except AttributeError:
try:
return super(Leaf, self).__getitem__(self._get_key(key))
except KeyError:
raise AttributeError()
def __setattr__(self, key, value):
try:
object.__getattr__(self, key)
object.__setattr__(self, key, value)
except AttributeError:
key = self._get_key(key)
if key == "@context":
value = self.get_context(value)
elif key == "@id":
value = self.get_id(value)
if key[0] == "_":
object.__setattr__(self, key, value)
else:
if value is None:
try:
super(Leaf, self).__delitem__(key)
except KeyError:
pass
else:
super(Leaf, self).__setitem__(key, value)
def get_id(self, id):
"""
Get id, dealing with prefixes
"""
# This is not the most elegant solution to change the @id attribute,
# but it is the quickest way to have it included in the dictionary
# without extra boilerplate.
if id and self._prefix and ":" not in id:
return "{}{}".format(self._prefix, id)
else:
return id
def __delattr__(self, key):
if key in self.__dict__:
del self.__dict__[key]
else:
super(Leaf, self).__delitem__(self._get_key(key))
def _get_key(self, key):
if key[0] == "_":
return key
elif key in ["context", "id"]:
return "@{}".format(key)
else:
return key
@staticmethod @staticmethod
def get_context(context): def get_context(context):
@ -95,22 +27,14 @@ class Leaf(dict):
return contexts return contexts
elif isinstance(context, dict): elif isinstance(context, dict):
return context return context
elif isinstance(context, str): elif isinstance(context, string_types):
try: try:
with open(context) as f: with open(context) as f:
return json.loads(f.read()) return json.loads(f.read())
except IOError: except IOError:
return context return context
else:
def compact(self): raise AttributeError('Please, provide a valid context')
return jsonld.compact(self, self.get_context(self.context))
def frame(self, frame=None, options=None):
if frame is None:
frame = self._frame
if options is None:
options = {}
return jsonld.frame(self, frame, options)
def jsonld(self, frame=None, options=None, def jsonld(self, frame=None, options=None,
context=None, removeContext=None): context=None, removeContext=None):
@ -163,92 +87,32 @@ class Leaf(dict):
status=self.get("status", 200), status=self.get("status", 200),
headers=headers, headers=headers,
mimetype="application/json") mimetype="application/json")
class Entry(JSONLD):
pass
class Response(Leaf): class Sentiment(JSONLD):
_context = Leaf.get_context("{}/context.jsonld".format( pass
os.path.dirname(os.path.realpath(__file__))))
_frame = {
"@context": _context,
"analysis": {
"@explicit": True,
"maxPolarityValue": {},
"minPolarityValue": {},
"name": {},
"version": {},
},
"entries": {}
}
def __init__(self, *args, **kwargs):
context = kwargs.pop("context", None)
frame = kwargs.pop("frame", None)
if context is None:
context = self._context
self.context = context
super(Response, self).__init__(
*args, context=context, frame=frame, **kwargs)
if self._frame is not None and "entries" in self._frame:
self.analysis = []
self.entries = []
def jsonld(self, frame=None, options=None, context=None, removeContext={}):
return super(Response, self).jsonld(frame,
options,
context,
removeContext)
class Entry(Leaf): class EmotionSet(JSONLD):
_context = { pass
"@vocab": ("http://persistence.uni-leipzig.org/"
"nlp2rdf/ontologies/nif-core#")
}
def __init__(self, text=None, emotion_sets=None, opinions=None, **kwargs):
super(Entry, self).__init__(**kwargs)
if text:
self.text = text
self.emotionSets = emotion_sets if emotion_sets else []
self.opinions = opinions if opinions else []
class Opinion(Leaf): class Emotion(JSONLD):
_context = { pass
"@vocab": "http://www.gsi.dit.upm.es/ontologies/marl/ns#"
}
def __init__(self, polarityValue=None, hasPolarity=None, *args, **kwargs):
super(Opinion, self).__init__(*args,
**kwargs)
if polarityValue is not None:
self.hasPolarityValue = polarityValue
if hasPolarity is not None:
self.hasPolarity = hasPolarity
class EmotionSet(Leaf): class Suggestion(JSONLD):
_context = {} pass
def __init__(self, emotions=None, *args, **kwargs): class Error(BaseException, JSONLD):
if not emotions:
emotions = []
super(EmotionSet, self).__init__(context=EmotionSet._context,
*args,
**kwargs)
self.emotions = emotions or []
class Emotion(Leaf):
_context = {}
class Error(Leaf):
# A better pattern would be this: # A better pattern would be this:
# http://flask.pocoo.org/docs/0.10/patterns/apierrors/ # htp://flask.pocoo.org/docs/0.10/patterns/apierrors/
_frame = {} _frame = {}
_context = {} _context = {}
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(Error, self).__init__(*args, **kwargs) self.message = kwargs.get('message', None)
super(Error, self).__init__(*args)

View File

@ -72,8 +72,8 @@ class SenpyPlugin(Leaf):
def __init__(self, info=None): def __init__(self, info=None):
if not info: if not info:
raise ValueError(("You need to provide configuration" raise Error(message=("You need to provide configuration"
"information for the plugin.")) "information for the plugin."))
logger.debug("Initialising {}".format(info)) logger.debug("Initialising {}".format(info))
super(SenpyPlugin, self).__init__() super(SenpyPlugin, self).__init__()
self.name = info["name"] self.name = info["name"]
@ -137,7 +137,7 @@ class ShelfMixin(object):
@property @property
def sh(self): def sh(self):
if not hasattr(self, '_sh') or not self._sh: if not hasattr(self, '_sh') or self._sh is None:
self._sh = shelve.open(self.shelf_file, writeback=True) self._sh = shelve.open(self.shelf_file, writeback=True)
return self._sh return self._sh

View File

@ -1,3 +1,4 @@
from __future__ import print_function
import os import os
import logging import logging
@ -31,7 +32,7 @@ class ExtensionsTest(TestCase):
""" Discovery of plugins in given folders. """ """ Discovery of plugins in given folders. """
# noinspection PyProtectedMember # noinspection PyProtectedMember
assert self.dir in self.senpy._search_folders assert self.dir in self.senpy._search_folders
print self.senpy.plugins print(self.senpy.plugins)
assert "Dummy" in self.senpy.plugins assert "Dummy" in self.senpy.plugins
def test_enabling(self): def test_enabling(self):

View File

@ -59,7 +59,7 @@ class ModelsTest(TestCase):
assert("entries" in js) assert("entries" in js)
assert("analysis" in js) assert("analysis" in js)
resp = r6.flask() resp = r6.flask()
received = json.loads(resp.data) received = json.loads(resp.data.decode())
logging.debug("Response: %s", js) logging.debug("Response: %s", js)
assert(received["entries"]) assert(received["entries"])
assert(received["entries"][0]["text"] == "Just testing") assert(received["entries"][0]["text"] == "Just testing")