From 930191549bf54dffcada15564f4d5da4ef2e1cfe Mon Sep 17 00:00:00 2001 From: Jonathan Yu Date: Mon, 19 Nov 2018 13:19:12 +1100 Subject: [PATCH 1/6] adding nc2schemaorg function --- nc2rdf/bald2schemaorg_mappings.json | 8 +++ nc2rdf/nc2rdf.py | 80 +++++++++++++++++++++++++++-- 2 files changed, 84 insertions(+), 4 deletions(-) create mode 100644 nc2rdf/bald2schemaorg_mappings.json diff --git a/nc2rdf/bald2schemaorg_mappings.json b/nc2rdf/bald2schemaorg_mappings.json new file mode 100644 index 0000000..9eadd25 --- /dev/null +++ b/nc2rdf/bald2schemaorg_mappings.json @@ -0,0 +1,8 @@ +[ + { "bald" : "summary", "schemaorg": "description" }, + { "bald" : "title", "schemaorg": "name" }, + { "bald" : "id", "schemaorg": "identifier" }, + { "bald" : "keywords", "schemaorg": "keywords" }, + { "bald" : "license", "schemaorg": "license" }, + { "bald" : "standard_name", "schemaorg": "variableMeasured" } +] diff --git a/nc2rdf/nc2rdf.py b/nc2rdf/nc2rdf.py index 4a91e32..14848cd 100644 --- a/nc2rdf/nc2rdf.py +++ b/nc2rdf/nc2rdf.py @@ -5,14 +5,79 @@ import netCDF4 import numpy as np import bald +import rdflib +import json +from rdflib import Namespace, BNode, URIRef, Literal +from rdflib.namespace import RDF + + + +def getBasename(urlstr): + return os.path.basename(urlstr) + +def baldgraph2schemaorg(graph): + """ + Input: netCDF file + Transforms to a rdflib.Graph bald style + Returns a new graph in schema.org profile + """ + #load mappings + mapping_idx = {} + mapping_data = [] + with open('bald2schemaorg_mappings.json' , 'r') as f: + mapping_data = json.load(f) + + for item in mapping_data: + mapping_idx[item['bald']] = item['schemaorg'] + + qres = graph.query( + """PREFIX bald: + SELECT DISTINCT ?pred ?value + WHERE { + ?c a bald:Container . + ?c ?pred ?value + }""") + + schema_g = rdflib.Graph() + container = BNode() + so = Namespace("http://schema.org/") + schema_g.add( (container, URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), so.Dataset) ) + + for row in qres: + currField = getBasename(str(row[0])).strip() + #print(getBasename(str(row[0])) + ' (type: ' + str(type(row[0])) + ")" + " :: " + row[1] + ' (type: ' + str(type(row[1])) + ")") + if(currField in mapping_idx.keys()): + print('schemaorg:' + mapping_idx[currField], "\t", row[1]) + predUri = URIRef("http://schema.org/" + mapping_idx[currField]) + lit = Literal(row[1]) + schema_g.add( (container, predUri, lit) ) + return schema_g + +def nc2schemaorg(ncfilename, outformat, baseuri=None): + root_container = bald.load_netcdf(ncfilename, baseuri=baseuri) + graph = root_container.rdfgraph() + schema_g = baldgraph2schemaorg(graph) + + if(outformat == 'json-ld'): + context = "http://schema.org/" + s = schema_g.serialize(format=outformat, context=context, indent=4).decode("utf-8") + else: + s = schema_g.serialize(format=outformat).decode("utf-8") + print(s) def nc2rdf(ncfilename, outformat, baseuri=None): - #print("nc2rdf test") - #print(ncfile) root_container = bald.load_netcdf(ncfilename, baseuri=baseuri) ttl = root_container.rdfgraph().serialize(format=outformat).decode("utf-8") print(ttl) +def cdl2schemaorg(cdl_file, outformat, baseuri=None): + tfile, tfilename = tempfile.mkstemp('.nc') + subprocess.check_call(['ncgen', '-o', tfilename, cdl_file]) + schema_g = nc2schemaorg(tfilename, outformat, baseuri=baseuri) + os.close(tfile) + os.remove(tfilename) + return schema_g + def cdl2rdf(cdl_file, outformat, baseuri=None): #print("cdl2rdf test") #print(cdl_file) @@ -32,13 +97,20 @@ def cdl2rdf(cdl_file, outformat, baseuri=None): parser.add_argument('--baseuri', action="store", dest="baseuri", help="Base URI for the graph") parser.add_argument('--cdl', action="store_true", dest="isCDL", default=False, help="Flag to indicate file is CDL") parser.add_argument('--nc', action="store_true", dest="isNC", default=False, help="Flag to indicate file is netCDF") + parser.add_argument('--schema-org', action="store_true", dest="isSchemaOrgOutput", default=False, help="Flag to indicate if schema.org output activated") parser.add_argument("ncfile", help="Path for the netCDF file") args = parser.parse_args() if(args.isCDL or args.ncfile.endswith(".cdl") or args.ncfile.endswith('.CDL')): - cdl2rdf(args.ncfile, args.format, baseuri=args.baseuri) + if(args.isSchemaOrgOutput): + cdl2schemaorg(args.ncfile, args.format, baseuri=args.baseuri) + else: + cdl2rdf(args.ncfile, args.format, baseuri=args.baseuri) elif(args.isNC or args.ncfile.endswith(".nc") or args.ncfile.endswith('.NC')): - nc2rdf(args.ncfile, args.format, baseuri=args.baseuri) + if(args.isSchemaOrgOutput): + nc2schemaorg(args.ncfile, args.format, baseuri=args.baseuri) + else: + nc2rdf(args.ncfile, args.format, baseuri=args.baseuri) else: print("Unrecognised file suffix. Please indicate if CDL or NC via --cdl or --nc"); From 2678a9bc0b70d19546fe4c70d56f3ccab7c57270 Mon Sep 17 00:00:00 2001 From: Jonathan Yu Date: Mon, 19 Nov 2018 13:23:19 +1100 Subject: [PATCH 2/6] ad reame --- nc2rdf/README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/nc2rdf/README.md b/nc2rdf/README.md index 43db903..40b54cd 100644 --- a/nc2rdf/README.md +++ b/nc2rdf/README.md @@ -31,4 +31,19 @@ $ python nc2rdf.py -o ttl myfile.nc $ python nc2rdf.py -o xml myfile.nc ``` +## nc2schemaorg + +This feature provides users a way to create schema.org descriptions from +ACDD/CF/NUG conformant values in a nc file. + +``` +$ python nc2rdf.py -o json-ld --schema-org [cdl or nc file] +``` + +Example: +``` +$ python nc2rdf.py -o json-ld --schema-org ../lib/bald/tests/integration/CDL/trajectoryProfile_template.cdl +``` + + Note: This command-line tool is experimental and is subject to changes, however serves as a prototype for accessing bald functions for netCDF related files to RDF. From 974d7790ad22ebd8d5eff34fa56e6e9fc235d107 Mon Sep 17 00:00:00 2001 From: Jonathan Yu Date: Mon, 19 Nov 2018 13:36:55 +1100 Subject: [PATCH 3/6] adding comments that this is a hack --- nc2rdf/nc2rdf.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/nc2rdf/nc2rdf.py b/nc2rdf/nc2rdf.py index 14848cd..2f91ce0 100644 --- a/nc2rdf/nc2rdf.py +++ b/nc2rdf/nc2rdf.py @@ -21,6 +21,9 @@ def baldgraph2schemaorg(graph): Transforms to a rdflib.Graph bald style Returns a new graph in schema.org profile """ + # HACK: The following mappings ignore prefixes as well as prefixes in nc file + # TODO: Fix references to prefixes/aliases proper + #load mappings mapping_idx = {} mapping_data = [] From 80347e48284cf4de9cb00a29c900d6e66992a4d7 Mon Sep 17 00:00:00 2001 From: Jonathan Yu Date: Tue, 20 Nov 2018 15:30:45 +1100 Subject: [PATCH 4/6] Commenting print --- nc2rdf/nc2rdf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nc2rdf/nc2rdf.py b/nc2rdf/nc2rdf.py index 2f91ce0..eae8c33 100644 --- a/nc2rdf/nc2rdf.py +++ b/nc2rdf/nc2rdf.py @@ -50,7 +50,7 @@ def baldgraph2schemaorg(graph): currField = getBasename(str(row[0])).strip() #print(getBasename(str(row[0])) + ' (type: ' + str(type(row[0])) + ")" + " :: " + row[1] + ' (type: ' + str(type(row[1])) + ")") if(currField in mapping_idx.keys()): - print('schemaorg:' + mapping_idx[currField], "\t", row[1]) + #print('schemaorg:' + mapping_idx[currField], "\t", row[1]) predUri = URIRef("http://schema.org/" + mapping_idx[currField]) lit = Literal(row[1]) schema_g.add( (container, predUri, lit) ) From 616e4716ee763d5da7073ccc05f7c4eeb754b05e Mon Sep 17 00:00:00 2001 From: Jonathan Yu Date: Tue, 20 Nov 2018 17:15:23 +1100 Subject: [PATCH 5/6] enable nc2rdf for urls --- lib/bald/__init__.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/bald/__init__.py b/lib/bald/__init__.py index 5f81270..f6c62f6 100644 --- a/lib/bald/__init__.py +++ b/lib/bald/__init__.py @@ -670,8 +670,10 @@ def load(afilepath): loader = netCDF4.Dataset else: raise ValueError('filepath suffix not supported: {}'.format(afilepath)) - if not os.path.exists(afilepath): - raise IOError('{} not found'.format(afilepath)) + #Disable this check for now to allow URL input + #TODO: Add feature to check both local files and files on the web, e.g. URLs + #if not os.path.exists(afilepath): + # raise IOError('{} not found'.format(afilepath)) try: f = loader(afilepath, "r") yield f From cd7b1db7a2adeee1e6dd480e0ed97debe7546c8d Mon Sep 17 00:00:00 2001 From: Jonathan Yu Date: Wed, 21 Nov 2018 10:20:57 +1100 Subject: [PATCH 6/6] adding feature to add url if input is a http/https url --- nc2rdf/nc2rdf.py | 41 +++++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/nc2rdf/nc2rdf.py b/nc2rdf/nc2rdf.py index eae8c33..96081dd 100644 --- a/nc2rdf/nc2rdf.py +++ b/nc2rdf/nc2rdf.py @@ -9,13 +9,24 @@ import json from rdflib import Namespace, BNode, URIRef, Literal from rdflib.namespace import RDF - - +try: + # python 3 + from urllib.parse import urlparse +except ImportError: + from urlparse import urlparse + +def isUrl(url): + try: + result = urlparse(url) + if all([result.scheme, result.netloc, result.path]) and (result.scheme == 'https' or result.scheme == 'http'): + return True + except: + return False def getBasename(urlstr): return os.path.basename(urlstr) -def baldgraph2schemaorg(graph): +def baldgraph2schemaorg(graph, path=None, baseuri=None): """ Input: netCDF file Transforms to a rdflib.Graph bald style @@ -42,16 +53,34 @@ def baldgraph2schemaorg(graph): }""") schema_g = rdflib.Graph() - container = BNode() + + if baseuri is not None: + container = URIRef(baseuri) + else: + container = BNode() + so = Namespace("http://schema.org/") schema_g.add( (container, URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"), so.Dataset) ) + if path is not None and isUrl(path): + predUri = URIRef("http://schema.org/url") + schema_g.add( (container, predUri, URIRef(path)) ) + for row in qres: currField = getBasename(str(row[0])).strip() #print(getBasename(str(row[0])) + ' (type: ' + str(type(row[0])) + ")" + " :: " + row[1] + ' (type: ' + str(type(row[1])) + ")") if(currField in mapping_idx.keys()): - #print('schemaorg:' + mapping_idx[currField], "\t", row[1]) predUri = URIRef("http://schema.org/" + mapping_idx[currField]) + if currField == 'keywords': + for x in row[1].split(','): + kw = x.strip() + if len(kw) == 0: + continue + lit = Literal(kw) + schema_g.add( (container, predUri, lit) ) + continue + + #print('schemaorg:' + mapping_idx[currField], "\t", row[1]) lit = Literal(row[1]) schema_g.add( (container, predUri, lit) ) return schema_g @@ -59,7 +88,7 @@ def baldgraph2schemaorg(graph): def nc2schemaorg(ncfilename, outformat, baseuri=None): root_container = bald.load_netcdf(ncfilename, baseuri=baseuri) graph = root_container.rdfgraph() - schema_g = baldgraph2schemaorg(graph) + schema_g = baldgraph2schemaorg(graph, path=ncfilename, baseuri=baseuri) if(outformat == 'json-ld'): context = "http://schema.org/"