Skip to content

Commit

Permalink
Merge pull request #16 from satra/enh/prefixes
Browse files Browse the repository at this point in the history
allow for additional prefixes or a modified context
  • Loading branch information
satra authored Apr 2, 2021
2 parents caaf5be + daf87ac commit 9597b24
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
10 changes: 8 additions & 2 deletions reproschema/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,19 @@ def validate(shapefile, path):
default="n-triples",
show_default=True,
)
@click.option(
"--prefixfile", default=None, type=click.Path(exists=True, dir_okay=False)
)
@click.option(
"--contextfile", default=None, type=click.Path(exists=True, dir_okay=False)
)
@click.argument("path", nargs=1, type=str)
def convert(path, format):
def convert(path, format, prefixfile, contextfile):
if not (path.startswith("http") or os.path.exists(path)):
raise ValueError(f"{path} must be a URL or an existing file or directory")
from .jsonldutils import to_newformat

print(to_newformat(path, format))
print(to_newformat(path, format, prefixfile, contextfile))


@main.command()
Expand Down
16 changes: 15 additions & 1 deletion reproschema/jsonldutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def validate_data(data, shape_file_path):
return conforms, v_text


def to_newformat(path, format):
def to_newformat(path, format, prefixfile=None, contextfile=None):
"""Convert a JSONLD document to n-triples format
Since PyLD requires an http url, a local server is started to serve the
Expand All @@ -87,6 +87,11 @@ def to_newformat(path, format):
A local path or remote url to convert to n-triples
format: str of enum
Returned format jsonld, n-triples, turtle
prefixfile: str
Prefixes to use when converting to turtle (ignored otherwise)
contextfile: str
Context to use for compaction when returning jsonld. If not provided,
a jsonld graph is returned.
Returns
-------
Expand All @@ -99,6 +104,10 @@ def to_newformat(path, format):
raise ValueError(f"{format} not in {supported_formats}")
data = load_file(path)
if format == "jsonld":
if contextfile is not None:
with open(contextfile) as fp:
context = json.load(fp)
data = jsonld.compact(data, context)
return json.dumps(data, indent=2)
kwargs = {"algorithm": "URDNA2015", "format": "application/n-quads"}
nt = jsonld.normalize(data, kwargs)
Expand All @@ -112,5 +121,10 @@ def to_newformat(path, format):
g.bind("nidm", "http://purl.org/nidash/nidm#")
g.bind("skos", "http://www.w3.org/2004/02/skos/core#")
g.bind("prov", "http://www.w3.org/ns/prov#")
if prefixfile is not None:
with open(prefixfile) as fp:
prefixes = json.load(fp)
for key, value in prefixes.items():
g.bind(key, value)
g.parse(data=nt, format="nt")
return g.serialize(format=format).decode()

0 comments on commit 9597b24

Please sign in to comment.