Better jsonld support

pull/8/head 0.2.9
J. Fernando Sánchez 10 years ago
parent 2f7a8d7267
commit 2834967026

@ -1,3 +1,4 @@
include requirements.txt include requirements.txt
include README.md include README.md
include senpy/context.jsonld include senpy/context.jsonld
recursive-include *.senpy

@ -22,6 +22,8 @@ This class shows how to use the nif_server module to create custom services.
import config import config
from flask import Flask from flask import Flask
from senpy.extensions import Senpy from senpy.extensions import Senpy
import logging
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__) app = Flask(__name__)

@ -36,7 +36,7 @@ class Sentiment140Plugin(SentimentPlugin):
elif polarity_value < 50: elif polarity_value < 50:
polarity = "marl:Negative" polarity = "marl:Negative"
entry = Entry(text=params["input"]) entry = Entry(text=params["input"])
opinion = Opinion(polarity=polarity, polarity_value=polarity_value) opinion = Opinion(hasPolarity=polarity, polarityValue=polarity_value)
entry.opinions.append(opinion) entry.opinions.append(opinion)
entry.language = lang entry.language = lang
response.entries.append(entry) response.entries.append(entry)

@ -8,25 +8,26 @@
"nif": "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#", "nif": "http://persistence.uni-leipzig.org/nlp2rdf/ontologies/nif-core#",
"onyx": "http://www.gsi.dit.upm.es/ontologies/onyx/ns#", "onyx": "http://www.gsi.dit.upm.es/ontologies/onyx/ns#",
"emotions": { "emotions": {
"@id": "onyx:hasEmotionSet", "@container": "@set",
"@type": "onyx:EmotionSet" "@id": "onyx:hasEmotionSet"
}, },
"opinions": { "opinions": {
"@container": "@list", "@container": "@set",
"@id": "marl:hasOpinion", "@id": "marl:hasOpinion"
"@type": "marl:Opinion"
}, },
"prov": "http://www.w3.org/ns/prov#", "prov": "http://www.w3.org/ns/prov#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#", "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"analysis": { "analysis": {
"@container": "@set",
"@id": "prov:wasInformedBy" "@id": "prov:wasInformedBy"
}, },
"entries": { "entries": {
"@container": "@set",
"@id": "prov:generated" "@id": "prov:generated"
}, },
"strings": { "strings": {
"@reverse": "nif:hasContext", "@container": "@set",
"@type": "nif:String" "@reverse": "nif:hasContext"
}, },
"date": "date":
{ {

@ -75,7 +75,7 @@ class Senpy(object):
@property @property
def default_plugin(self): def default_plugin(self):
candidates = self.filter_plugins(enabled=True) candidates = self.filter_plugins(enabled=True)
if len(candidates) > 1: if len(candidates) > 0:
candidate = candidates.keys()[0] candidate = candidates.keys()[0]
logger.debug("Default: {}".format(candidate)) logger.debug("Default: {}".format(candidate))
return candidate return candidate
@ -169,4 +169,4 @@ class Senpy(object):
def sentiment_plugins(self): def sentiment_plugins(self):
""" Return only the sentiment plugins """ """ Return only the sentiment plugins """
return {p: plugin for p, plugin in self.plugins.items() if return {p: plugin for p, plugin in self.plugins.items() if
isinstance(plugin, SentimentPlugin)} isinstance(plugin, SentimentPlugin)}

@ -4,35 +4,48 @@ from collections import defaultdict
class Leaf(defaultdict): class Leaf(defaultdict):
def __init__(self, ofclass=list): def __init__(self, context=None, ofclass=list):
super(Leaf, self).__init__(ofclass) super(Leaf, self).__init__(ofclass)
if context:
self.context = context
def __getattr__(self, name): def __getattr__(self, name):
return super(Leaf, self).__getitem__(name) if name is not "context":
return super(Leaf, self).__getitem__(name)
return self["@context"]
def __setattr__(self, name, value): def __setattr__(self, name, value):
self[name] = value name = "@context" if name is "context" else name
self[name] = self.get_context(value)
def __delattr__(self, name): def __delattr__(self, name):
return super(Leaf, self).__delitem__(name) return super(Leaf, self).__delitem__(name)
@staticmethod
def get_context(context):
if isinstance(context, list):
contexts = []
for c in context:
contexts.append(Response.get_context(c))
return contexts
elif isinstance(context, dict):
return context
elif isinstance(context, basestring):
try:
with open(context) as f:
return json.loads(f.read())
except IOError:
return context
class Response(Leaf): class Response(Leaf):
def __init__(self, context=None): def __init__(self, context=None, *args, **kwargs):
super(Response, self).__init__()
self["analysis"] = []
self["entries"] = []
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__)))
if isinstance(context, dict): super(Response, self).__init__(*args, context=context, **kwargs)
self["@context"] = context self["analysis"] = []
if isinstance(context, str) or isinstance(context, unicode): self["entries"] = []
try:
with open(context) as f:
self["@context"] = json.loads(f.read())
except IOError:
self["@context"] = context
class Entry(Leaf): class Entry(Leaf):
@ -47,17 +60,27 @@ class Entry(Leaf):
class Opinion(Leaf): class Opinion(Leaf):
def __init__(self, polarity_value=None, polarity=None, **kwargs): opinionContext = {
super(Opinion, self).__init__(**kwargs) "@vocab": "http://www.gsi.dit.upm.es/ontologies/marl/ns#"
if polarity_value is not None: }
self.polarity_value = polarity_value def __init__(self, polarityValue=None, hasPolarity=None, *args, **kwargs):
if polarity is not None: super(Opinion, self).__init__(context=self.opinionContext,
self.polarity = polarity *args,
**kwargs)
if polarityValue is not None:
self.polarityValue = polarityValue
if hasPolarity is not None:
self.hasPolarity = hasPolarity
class EmotionSet(Leaf): class EmotionSet(Leaf):
def __init__(self, emotions=None, **kwargs): emotionContext = {
"@vocab": "http://www.gsi.dit.upm.es/ontologies/onyx/ns#"
}
def __init__(self, emotions=None, *args, **kwargs):
if not emotions: if not emotions:
emotions = [] emotions = []
super(EmotionSet, self).__init__(**kwargs) super(EmotionSet, self).__init__(context=self.emotionContext,
*args,
**kwargs)
self.emotions = emotions or [] self.emotions = emotions or []

@ -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.2.8" VERSION = "0.2.9"
print(reqs) print(reqs)

Loading…
Cancel
Save