1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
|
# -*- coding: utf-8 -*-
"""
Implementation of the JSON-LD Context structure. See:
http://json-ld.org/
"""
from collections import namedtuple
from rdflib.namespace import RDF
from ._compat import basestring, unicode
from .keys import (
BASE,
CONTAINER,
CONTEXT,
GRAPH,
ID,
INDEX,
LANG,
LIST,
REV,
SET,
TYPE,
VALUE,
VOCAB,
)
from . import errors
from .util import source_to_json, urljoin, urlsplit, split_iri, norm_url
NODE_KEYS = set([LANG, ID, TYPE, VALUE, LIST, SET, REV, GRAPH])
class Defined(int):
pass
UNDEF = Defined(0)
class Context(object):
def __init__(self, source=None, base=None):
self.language = None
self.vocab = None
self.base = base
self.doc_base = base
self.terms = {}
# _alias maps NODE_KEY to list of aliases
self._alias = {}
self._lookup = {}
self._prefixes = {}
self.active = False
if source:
self.load(source)
@property
def base(self):
return self._base
@base.setter
def base(self, base):
if base:
hash_index = base.find("#")
if hash_index > -1:
base = base[0:hash_index]
self._base = (
self.resolve_iri(base)
if (hasattr(self, "_base") and base is not None)
else base
)
self._basedomain = "%s://%s" % urlsplit(base)[0:2] if base else None
def subcontext(self, source):
# IMPROVE: to optimize, implement SubContext with parent fallback support
ctx = Context()
ctx.language = self.language
ctx.vocab = self.vocab
ctx.base = self.base
ctx.doc_base = self.doc_base
ctx._alias = self._alias.copy()
ctx.terms = self.terms.copy()
ctx._lookup = self._lookup.copy()
ctx._prefixes = self._prefixes.copy()
ctx.load(source)
return ctx
def get_id(self, obj):
return self._get(obj, ID)
def get_type(self, obj):
return self._get(obj, TYPE)
def get_language(self, obj):
return self._get(obj, LANG)
def get_value(self, obj):
return self._get(obj, VALUE)
def get_graph(self, obj):
return self._get(obj, GRAPH)
def get_list(self, obj):
return self._get(obj, LIST)
def get_set(self, obj):
return self._get(obj, SET)
def get_rev(self, obj):
return self._get(obj, REV)
def _get(self, obj, key):
for alias in self._alias.get(key, []):
if alias in obj:
return obj.get(alias)
return obj.get(key)
def get_key(self, key):
return self.get_keys(key)[0]
def get_keys(self, key):
return self._alias.get(key, [key])
lang_key = property(lambda self: self.get_key(LANG))
id_key = property(lambda self: self.get_key(ID))
type_key = property(lambda self: self.get_key(TYPE))
value_key = property(lambda self: self.get_key(VALUE))
list_key = property(lambda self: self.get_key(LIST))
rev_key = property(lambda self: self.get_key(REV))
graph_key = property(lambda self: self.get_key(GRAPH))
def add_term(
self,
name,
idref,
coercion=UNDEF,
container=UNDEF,
language=UNDEF,
reverse=False,
):
term = Term(idref, name, coercion, container, language, reverse)
self.terms[name] = term
self._lookup[(idref, coercion or language, container, reverse)] = term
self._prefixes[idref] = name
def find_term(
self, idref, coercion=None, container=UNDEF, language=None, reverse=False
):
lu = self._lookup
if coercion is None:
coercion = language
if coercion is not UNDEF and container:
found = lu.get((idref, coercion, container, reverse))
if found:
return found
if coercion is not UNDEF:
found = lu.get((idref, coercion, UNDEF, reverse))
if found:
return found
if container:
found = lu.get((idref, coercion, container, reverse))
if found:
return found
elif language:
found = lu.get((idref, UNDEF, LANG, reverse))
if found:
return found
else:
found = lu.get((idref, coercion or UNDEF, SET, reverse))
if found:
return found
return lu.get((idref, UNDEF, UNDEF, reverse))
def resolve(self, curie_or_iri):
iri = self.expand(curie_or_iri, False)
if self.isblank(iri):
return iri
return self.resolve_iri(iri)
def resolve_iri(self, iri):
return norm_url(self._base, iri)
def isblank(self, ref):
return ref.startswith("_:")
def expand(self, term_curie_or_iri, use_vocab=True):
if use_vocab:
term = self.terms.get(term_curie_or_iri)
if term:
return term.id
is_term, pfx, local = self._prep_expand(term_curie_or_iri)
if pfx == "_":
return term_curie_or_iri
if pfx is not None:
ns = self.terms.get(pfx)
if ns and ns.id:
return ns.id + local
elif is_term and use_vocab:
if self.vocab:
return self.vocab + term_curie_or_iri
return None
return self.resolve_iri(term_curie_or_iri)
def shrink_iri(self, iri):
ns, name = split_iri(unicode(iri))
pfx = self._prefixes.get(ns)
if pfx:
return ":".join((pfx, name))
elif self._base:
if unicode(iri) == self._base:
return ""
elif iri.startswith(self._basedomain):
return iri[len(self._basedomain) :]
return iri
def to_symbol(self, iri):
iri = unicode(iri)
term = self.find_term(iri)
if term:
return term.name
ns, name = split_iri(iri)
if ns == self.vocab:
return name
pfx = self._prefixes.get(ns)
if pfx:
return ":".join((pfx, name))
return iri
def load(self, source, base=None):
self.active = True
sources = []
source = source if isinstance(source, list) else [source]
self._prep_sources(base, source, sources)
for source_url, source in sources:
self._read_source(source, source_url)
def _prep_sources(
self, base, inputs, sources, referenced_contexts=None, in_source_url=None
):
referenced_contexts = referenced_contexts or set()
for source in inputs:
if isinstance(source, basestring):
source_url = urljoin(base, source)
if source_url in referenced_contexts:
raise errors.RECURSIVE_CONTEXT_INCLUSION
referenced_contexts.add(source_url)
source = source_to_json(source_url)
if CONTEXT not in source:
raise errors.INVALID_REMOTE_CONTEXT
else:
source_url = in_source_url
if isinstance(source, dict):
if CONTEXT in source:
source = source[CONTEXT]
source = source if isinstance(source, list) else [source]
if isinstance(source, list):
self._prep_sources(
base, source, sources, referenced_contexts, source_url
)
else:
sources.append((source_url, source))
def _read_source(self, source, source_url=None):
self.vocab = source.get(VOCAB, self.vocab)
for key, value in source.items():
if key == LANG:
self.language = value
elif key == VOCAB:
continue
elif key == BASE:
if source_url:
continue
self.base = value
else:
self._read_term(source, key, value)
def _read_term(self, source, name, dfn):
idref = None
if isinstance(dfn, dict):
# term = self._create_term(source, key, value)
rev = dfn.get(REV)
idref = rev or dfn.get(ID, UNDEF)
if idref == TYPE:
idref = unicode(RDF.type)
elif idref is not UNDEF:
idref = self._rec_expand(source, idref)
elif ":" in name:
idref = self._rec_expand(source, name)
elif self.vocab:
idref = self.vocab + name
coercion = dfn.get(TYPE, UNDEF)
if coercion and coercion not in (ID, TYPE, VOCAB):
coercion = self._rec_expand(source, coercion)
self.add_term(
name,
idref,
coercion,
dfn.get(CONTAINER, UNDEF),
dfn.get(LANG, UNDEF),
bool(rev),
)
else:
if isinstance(dfn, unicode):
idref = self._rec_expand(source, dfn)
self.add_term(name, idref)
if idref in NODE_KEYS:
self._alias.setdefault(idref, []).append(name)
def _rec_expand(self, source, expr, prev=None):
if expr == prev or expr in NODE_KEYS:
return expr
is_term, pfx, nxt = self._prep_expand(expr)
if pfx:
iri = self._get_source_id(source, pfx)
if iri is None:
if pfx + ":" == self.vocab:
return expr
else:
term = self.terms.get(pfx)
if term:
iri = term.id
if iri is None:
nxt = expr
else:
nxt = iri + nxt
else:
nxt = self._get_source_id(source, nxt) or nxt
if ":" not in nxt and self.vocab:
return self.vocab + nxt
return self._rec_expand(source, nxt, expr)
def _prep_expand(self, expr):
if ":" not in expr:
return True, None, expr
pfx, local = expr.split(":", 1)
if not local.startswith("//"):
return False, pfx, local
else:
return False, None, expr
def _get_source_id(self, source, key):
# .. from source dict or if already defined
term = source.get(key)
if term is None:
dfn = self.terms.get(key)
if dfn:
term = dfn.id
elif isinstance(term, dict):
term = term.get(ID)
return term
def _term_dict(self, term):
tdict = {ID: self.shrink_iri(term.id)}
if term.type != UNDEF:
tdict[TYPE] = self.shrink_iri(term.type)
if term.container != UNDEF:
tdict[CONTAINER] = term.container
if term.language != UNDEF:
tdict[LANG] = term.language
if term.reverse:
tdict[REV] = term.reverse
if len(tdict) == 1:
return tdict[ID]
return tdict
def to_dict(self):
r = {v: k for (k, v) in self._prefixes.items()}
r.update({t.name: self._term_dict(t) for t in self._lookup.values()})
if self.base:
r[BASE] = self.base
if self.language:
r[LANG] = self.language
return r
Term = namedtuple("Term", "id, name, type, container, language, reverse")
Term.__new__.__defaults__ = (UNDEF, UNDEF, UNDEF, False)
|