1 """Helper features for working with librdf
3 from __future__ import print_function, unicode_literals
6 from datetime import datetime
8 from urlparse import urlparse, urlunparse
9 from urllib2 import urlopen
14 from pkg_resources import resource_listdir, resource_string
17 import lxml.html.clean
20 logger = logging.getLogger(__name__)
22 from htsworkflow.util.rdfns import *
24 SCHEMAS_URL='http://jumpgate.caltech.edu/phony/schemas'
25 INFERENCE_URL='http://jumpgate.caltech.edu/phony/inference'
27 ISOFORMAT_MS = "%Y-%m-%dT%H:%M:%S.%f"
28 ISOFORMAT_SHORT = "%Y-%m-%dT%H:%M:%S"
30 def sparql_query(model, query_filename, output_format='text'):
31 """Execute sparql query from file
33 logger.info("Opening: %s" % (query_filename,))
34 query_body = open(query_filename, 'r').read()
35 query = RDF.SPARQLQuery(query_body)
36 results = query.execute(model)
37 if output_format == 'html':
38 html_query_results(results)
40 display_query_results(results)
43 def display_query_results(results):
44 """A very simple display of sparql query results showing name value pairs
47 for k, v in row.items()[::-1]:
48 print("{0}: {1}".format(k, v))
51 def html_query_results(result_stream):
52 from django.conf import settings
53 from django.template import Context, loader
55 # I did this because I couldn't figure out how to
56 # get simplify_rdf into the django template as a filter
57 class Simplified(object):
58 def __init__(self, value):
59 self.simple = simplify_rdf(value)
60 if value.is_resource():
65 template = loader.get_template('rdf_report.html')
67 for row in result_stream:
68 new_row = collections.OrderedDict()
70 for k,v in row.items():
71 new_row[k] = Simplified(v)
72 results.append(new_row)
73 context = Context({'results': results,})
74 print(template.render(context))
76 def blankOrUri(value=None):
77 """Return a blank node for None or a resource node for strings.
82 elif type(value) in types.StringTypes:
83 node = RDF.Node(uri_string=value)
84 elif isinstance(value, RDF.Node):
90 def toTypedNode(value, language="en"):
91 """Convert a python variable to a RDF Node with its closest xsd type
93 if type(value) == types.BooleanType:
94 value_type = xsdNS['boolean'].uri
99 elif type(value) in (types.IntType, types.LongType):
100 value_type = xsdNS['decimal'].uri
101 value = unicode(value)
102 elif type(value) == types.FloatType:
103 value_type = xsdNS['float'].uri
104 value = unicode(value)
105 elif isinstance(value, datetime):
106 value_type = xsdNS['dateTime'].uri
107 if value.microsecond == 0:
108 value = value.strftime(ISOFORMAT_SHORT)
110 value = value.strftime(ISOFORMAT_MS)
113 value = unicode(value)
115 if value_type is not None:
116 node = RDF.Node(literal=value, datatype=value_type)
118 node = RDF.Node(literal=unicode(value).encode('utf-8'), language=language)
122 def fromTypedNode(node):
123 """Convert a typed RDF Node to its closest python equivalent
125 if not isinstance(node, RDF.Node):
127 if node.is_resource():
130 value_type = get_node_type(node)
131 literal = node.literal_value['string']
132 literal_lower = literal.lower()
134 if value_type == 'boolean':
135 if literal_lower in ('1', 'yes', 'true'):
137 elif literal_lower in ('0', 'no', 'false'):
140 raise ValueError("Unrecognized boolean %s" % (literal,))
141 elif value_type == 'integer':
143 elif value_type == 'decimal' and literal.find('.') == -1:
145 elif value_type in ('decimal', 'float', 'double'):
146 return float(literal)
147 elif value_type in ('string'):
149 elif value_type in ('dateTime'):
151 return datetime.strptime(literal, ISOFORMAT_MS)
153 return datetime.strptime(literal, ISOFORMAT_SHORT)
157 def get_node_type(node):
158 """Return just the base name of a XSD datatype:
159 e.g. http://www.w3.org/2001/XMLSchema#integer -> integer
161 # chop off xml schema declaration
162 value_type = node.literal_value['datatype']
163 if value_type is None:
166 value_type = str(value_type)
167 return value_type.replace(str(xsdNS[''].uri), '')
170 def simplify_rdf(value):
171 """Return a short name for a RDF object
172 e.g. The last part of a URI or an untyped string.
174 if isinstance(value, RDF.Node):
175 if value.is_resource():
176 name = simplify_uri(str(value.uri))
177 elif value.is_blank():
180 name = value.literal_value['string']
181 elif isinstance(value, RDF.Uri):
182 name = split_uri(str(value))
188 def simplify_uri(uri):
189 """Split off the end of a uri
191 >>> simplify_uri('http://asdf.org/foo/bar')
193 >>> simplify_uri('http://asdf.org/foo/bar#bleem')
195 >>> simplify_uri('http://asdf.org/foo/bar/')
197 >>> simplify_uri('http://asdf.org/foo/bar?was=foo')
200 if isinstance(uri, RDF.Node):
201 if uri.is_resource():
204 raise ValueError("Can't simplify an RDF literal")
205 if isinstance(uri, RDF.Uri):
208 parsed = urlparse(uri)
209 if len(parsed.query) > 0:
211 elif len(parsed.fragment) > 0:
212 return parsed.fragment
213 elif len(parsed.path) > 0:
214 for element in reversed(parsed.path.split('/')):
217 raise ValueError("Unable to simplify %s" % (uri,))
219 def strip_namespace(namespace, term):
220 """Remove the namespace portion of a term
222 returns None if they aren't in common
224 if isinstance(term, RDF.Node):
225 if term.is_resource():
228 raise ValueError("This works on resources")
229 elif not isinstance(term, RDF.Uri):
230 raise ValueError("This works on resources")
232 if not term_s.startswith(namespace._prefix):
234 return term_s.replace(namespace._prefix, "")
237 def get_model(model_name=None, directory=None, use_contexts=True):
238 if directory is None:
239 directory = os.getcwd()
241 contexts = 'yes' if use_contexts else 'no'
243 if model_name is None:
244 storage = RDF.MemoryStorage(options_string="contexts='{}'".format(contexts))
245 logger.info("Using RDF Memory model")
247 options = "contexts='{0}',hash-type='bdb',dir='{1}'".format(contexts, directory)
248 storage = RDF.HashStorage(model_name,
250 logger.info("Using {0} with options {1}".format(model_name, options))
251 model = RDF.Model(storage)
255 def load_into_model(model, parser_name, path, ns=None):
256 if type(ns) in types.StringTypes:
259 if isinstance(path, RDF.Node):
260 if path.is_resource():
263 raise ValueError("url to load can't be a RDF literal")
265 url_parts = list(urlparse(path))
266 if len(url_parts[0]) == 0 or url_parts[0] == 'file':
267 url_parts[0] = 'file'
268 url_parts[2] = os.path.abspath(url_parts[2])
269 if parser_name is None or parser_name == 'guess':
270 parser_name = guess_parser_by_extension(path)
271 url = urlunparse(url_parts)
272 logger.info("Opening {0} with parser {1}".format(url, parser_name))
274 rdf_parser = RDF.Parser(name=parser_name)
282 statements = rdf_parser.parse_as_stream(url, ns)
285 except RDF.RedlandError as e:
286 errmsg = "RDF.RedlandError: {0} {1} tries remaining"
287 logger.error(errmsg.format(str(e), retries))
290 logger.warn("Unable to download %s", url)
293 conditionally_add_statement(model, s, ns)
295 def load_string_into_model(model, parser_name, data, ns=None):
296 ns = fixup_namespace(ns)
297 logger.debug("load_string_into_model parser={0}, len={1}".format(
298 parser_name, len(data)))
299 rdf_parser = RDF.Parser(name=parser_name)
301 for s in rdf_parser.parse_string_as_stream(data, ns):
302 conditionally_add_statement(model, s, ns)
305 def fixup_namespace(ns):
307 ns = RDF.Uri("http://localhost/")
308 elif type(ns) in types.StringTypes:
310 elif not(isinstance(ns, RDF.Uri)):
311 errmsg = "Namespace should be string or uri not {0}"
312 raise ValueError(errmsg.format(str(type(ns))))
316 def conditionally_add_statement(model, s, ns):
317 imports = owlNS['imports']
318 if s.predicate == imports:
320 logger.info("Importing %s" % (obj,))
321 load_into_model(model, None, obj, ns)
322 if s.object.is_literal():
323 value_type = get_node_type(s.object)
324 if value_type == 'string':
325 s.object = sanitize_literal(s.object)
326 model.add_statement(s)
329 def add_default_schemas(model, schema_path=None):
330 """Add default schemas to a model
331 Looks for turtle files in either htsworkflow/util/schemas
332 or in the list of directories provided in schema_path
335 schemas = resource_listdir(__name__, 'schemas')
337 schema = resource_string(__name__, 'schemas/' + s)
338 namespace = 'file://localhost/htsworkflow/schemas/'+s
339 add_schema(model, schema, namespace)
342 if type(schema_path) in types.StringTypes:
343 schema_path = [schema_path]
345 for path in schema_path:
346 for pathname in glob(os.path.join(path, '*.turtle')):
347 url = 'file://' + os.path.splitext(pathname)[0]
348 stream = open(pathname, 'r')
349 add_schema(model, stream, url)
352 def add_schema(model, schema, url):
353 """Add a schema to a model.
355 Main difference from 'load_into_model' is it tags it with
356 a RDFlib context so I can remove them later.
358 parser = RDF.Parser(name='turtle')
359 context = RDF.Node(RDF.Uri(SCHEMAS_URL))
360 for s in parser.parse_string_as_stream(schema, url):
362 model.append(s, context)
363 except RDF.RedlandError as e:
364 logger.error("%s with %s", str(e), str(s))
367 def remove_schemas(model):
368 """Remove statements labeled with our schema context"""
369 context = RDF.Node(RDF.Uri(SCHEMAS_URL))
370 model.context_remove_statements(context)
373 def sanitize_literal(node):
374 """Clean up a literal string
376 if not isinstance(node, RDF.Node):
377 raise ValueError("sanitize_literal only works on RDF.Nodes")
379 s = node.literal_value['string']
381 element = lxml.html.fromstring(s)
382 cleaner = lxml.html.clean.Cleaner(page_structure=False)
383 element = cleaner.clean_html(element)
384 text = lxml.html.tostring(element)
388 args = {'literal': text[p_len:-slash_p_len]}
390 args = {'literal': ''}
391 datatype = node.literal_value['datatype']
392 if datatype is not None:
393 args['datatype'] = datatype
394 language = node.literal_value['language']
395 if language is not None:
396 args['language'] = language
397 return RDF.Node(**args)
400 def guess_parser(content_type, pathname):
401 if content_type in ('application/rdf+xml',):
403 elif content_type in ('application/x-turtle',):
405 elif content_type in ('text/html',):
407 elif content_type is None or content_type in ('text/plain',):
408 return guess_parser_by_extension(pathname)
410 def guess_parser_by_extension(pathname):
411 _, ext = os.path.splitext(pathname)
412 if ext in ('.xml', '.rdf'):
414 elif ext in ('.html',):
416 elif ext in ('.turtle',):
420 def get_serializer(name='turtle'):
421 """Return a serializer with our standard prefixes loaded
423 writer = RDF.Serializer(name=name)
424 # really standard stuff
425 writer.set_namespace('rdf', rdfNS._prefix)
426 writer.set_namespace('rdfs', rdfsNS._prefix)
427 writer.set_namespace('owl', owlNS._prefix)
428 writer.set_namespace('dc', dcNS._prefix)
429 writer.set_namespace('xml', xmlNS._prefix)
430 writer.set_namespace('xsd', xsdNS._prefix)
431 writer.set_namespace('vs', vsNS._prefix)
432 writer.set_namespace('wot', wotNS._prefix)
434 # should these be here, kind of specific to an application
435 writer.set_namespace('htswlib', libraryOntology._prefix)
436 writer.set_namespace('ucscSubmission', submissionOntology._prefix)
437 writer.set_namespace('ucscDaf', dafTermOntology._prefix)
438 writer.set_namespace('geoSoft', geoSoftNS._prefix)
439 writer.set_namespace('encode3', encode3NS._prefix)
442 def get_turtle_header():
443 """Return a turtle header with our typical namespaces
445 serializer = get_serializer()
447 return serializer.serialize_model_to_string(empty)
449 def dump_model(model, destination=None):
450 if destination is None:
451 destination = sys.stdout
452 serializer = get_serializer()
453 destination.write(serializer.serialize_model_to_string(model))
454 destination.write(os.linesep)