Commit 8b806962 authored by lambdamusic's avatar lambdamusic

refactor

parent 1089f509
......@@ -25,10 +25,10 @@ Ontospy can be used either as an interactive command line interface (a
Calling the `ontospy` command from a terminal window launches a utility for scanning a knowledge model encoded in RDF (or any of its dialects e.g. RDFS, OWL or SKOS).
For example, if you pass a valid graph URI e.g.
For example, if you pass a valid graph URI:
```
$ ontospy scan http://purl.org/spar/frbr
$ ontospy ex http://purl.org/spar/frbr # ex = examine
```
Ontospy will extract and print out any ontology-related information contained in that graph.
......
......@@ -9,6 +9,7 @@ Summary of changes.
- allow to pass viztype from command line
- implicit/explicit classes and predicates switch '-x'
- this is useful to inspect a small RDF snippet for example too see what predicates are being used
- option to show raw RDF data (-r)
## December, 2018: v1.9.7
......
This page shows how to use Ontospy from the command line.
These are the commands available:
- `ontospy`: used to launch the Ontospy parser.
- `ontospy-shell`: used to launch the Ontospy command line interface.
- `ontospy-viz`: used to the launch the Ontospy visualization library.
> Note
If you install OntosPy via one of the suggested methods, appropriate executables for your platform should be compiled automatically and added to `usr/local/bin` (by default on unix-based systems).
### The `ontospy` command
A good place to start is the -h option:
```
Usage: ontospy [OPTIONS] [SOURCES]...
Ontospy is a command line inspector for RDF/OWL knowledge models.
Examples:
Inspect a local RDF file:
> ontospy /path/to/mymodel.rdf
List ontologies available in the local library:
> ontospy -l
Open FOAF vocabulary and save it to the local library:
> ontospy http://xmlns.com/foaf/spec/ -s
More info: <ontospy.readthedocs.org>
Options:
-b, --bootstrap BOOTSTRAP: bootstrap the local library.
-c, --cache CACHE: force caching of the local library (for faster
loading).
-d, --delete DELETE: remove an ontology from the local library.
-l, --library LIBRARY: list ontologies saved in the local library.
-s, --save SAVE: save a file/folder/url into the local library.
-r, --reset RESET: delete all files in the local library.
-u, --update UPDATE: enter new path for the local library.
-v, --verbose VERBOSE: show entities labels as well as URIs.
-w, --web WEB: import ontologies from remote repositories.
-h, --help Show this message and exit.
```
Just calling `ontospy` without any argument has the effect of listing out all RDF models saved in the local library. The first time you run it, there are none obviously so you might want to run the `ontospy -b` option to get started.
> Note
You can pass the Ontospy command either a single file or a folder path. In the second case it’ll try to load any RDF file found in that path (recursively). For example, the second option can be handy if you have a knowledge model which is split into multiple files.
Alternatively, you can also pass a valid graph URI as an argument to the `ontospy` command in order to print out useful ontology information:
```
> ontospy http://www.ifomis.org/bfo/1.1
# prints info about BFO resolving redirects etc..
Ontospy v1.7
Local library: </Users/michele.pasin/Dropbox/ontologies/ontospy-library/>
----------
.. trying rdf serialization: <xml>
..... success!
----------
Loaded 429 triples from <https://raw.githubusercontent.com/BFO-ontology/BFO/releases/1.1.1/bfo.owl>
started scanning...
----------
Ontologies found...: 1
Classes found......: 39
Properties found...: 9
Annotation.........: 9
Datatype...........: 0
Object.............: 0
SKOS Concepts......: 0
----------
Ontology Annotations
-----------
http://www.ifomis.org/bfo/1.1
=> http://purl.org/dc/elements/1.1/source
.... Pierre Grenon: "BFO in a Nutshell: A Bi-categorial Axiomatization of BFO and Comparison with DOLCE"
=> http://purl.org/dc/elements/1.1/language
.... en
=> http://purl.org/dc/elements/1.1/title
.... Basic Formal Ontology (BFO)
=> http://www.w3.org/1999/02/22-rdf-syntax-ns#type
.... http://www.w3.org/2002/07/owl#Ontology
### ...etc....
Class Taxonomy
----------
bfo:Entity
----snap:Continuant
--------snap:DependentContinuant
------------snap:GenericallyDependentContinuant
------------snap:SpecificallyDependentContinuant
----------------snap:Quality
----------------snap:RealizableEntity
--------------------snap:Disposition
--------------------snap:Function
--------------------snap:Role
--------snap:IndependentContinuant
------------snap:MaterialEntity
----------------snap:FiatObjectPart
----------------snap:Object
----------------snap:ObjectAggregate
------------snap:ObjectBoundary
------------snap:Site
--------snap:SpatialRegion
------------snap:OneDimensionalRegion
------------snap:ThreeDimensionalRegion
------------snap:TwoDimensionalRegion
------------snap:ZeroDimensionalRegion
----span:Occurrent
--------span:ProcessualEntity
------------span:FiatProcessPart
------------span:Process
------------span:ProcessAggregate
------------span:ProcessBoundary
------------span:ProcessualContext
--------span:SpatiotemporalRegion
------------span:ConnectedSpatiotemporalRegion
----------------span:SpatiotemporalInstant
----------------span:SpatiotemporalInterval
------------span:ScatteredSpatiotemporalRegion
--------span:TemporalRegion
------------span:ConnectedTemporalRegion
----------------span:TemporalInstant
----------------span:TemporalInterval
------------span:ScatteredTemporalRegion
Property Taxonomy
----------
dc:contributor
dc:creator
dc:format
dc:identifier
dc:language
dc:publisher
dc:rights
dc:source
dc:title
----------
Time: 3.42s
```
### The ontospy-shell command
```
> ontospy-shell -h
Usage: ontospy-shell [OPTIONS] [SOURCE]...
This application launches the Ontospy interactive shell.
Note: if a local path or URI of an RDF model is provided, that gets loaded
into the shell by default. E.g.:
> ontospy-shell path/to/mymodel.rdf
Options:
-h, --help Show this message and exit.
```
Calling `ontospy-shell` without any argument launches the shell. The shell is an interactive environment that lets you import, load and inspect vocabularies. For more examples on how that works, take a look at this video:
[![OntospyVideo](./wiki/images/ontospyvideo.jpg)](https://vimeo.com/169707591)
> Note: you can pass an argument in order to pre-load an RDF graph into the interactive session.
\ No newline at end of file
......@@ -44,6 +44,7 @@ from .core.manager import *
from .core.utils import *
SHELL_EXAMPLES = """
#### LEGACY
Quick Examples:
> ontospy ~/Desktop/mymodel.rdf # ==> inspect a local RDF file
......@@ -72,25 +73,17 @@ CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.group(invoke_without_command=True, context_settings=CONTEXT_SETTINGS)
@click.option(
'--extra',
'-x',
is_flag=True,
help=
'EXTRA-DATA: extract implicit types and predicates using basic inference rules. Note: by default ontospy extracts only classes/properties which are explictly declared.'
)
@click.option(
'--verbose', '-v', is_flag=True, help='VERBOSE: print out debug messages.')
@click.pass_context
def main_cli(ctx, extra=False, verbose=False):
def main_cli(ctx, verbose=False):
"""
Ontospy is a command line inspector for RDF/OWL models. Use the --help option with one of the commands listed below to find out more, or visit http://lambdamusic.github.io/Ontospy
Ontospy allows to extract and visualise ontology information included in RDF data. Use one of the commands listed below to find out more, or visit http://lambdamusic.github.io/ontospy
"""
sTime = time.time()
if ctx.obj is None: # Fix for bug (as of 3.0)
# https://github.com/pallets/click/issues/888
ctx.obj = {}
ctx.obj['EXTRA'] = extra
ctx.obj['VERBOSE'] = verbose
ctx.obj['STIME'] = sTime
......@@ -102,6 +95,50 @@ Ontospy is a command line inspector for RDF/OWL models. Use the --help option wi
# click.echo('I am about to invoke %s' % ctx.invoked_subcommand)
##
## EXAMINE COMMAND
##
@main_cli.command()
@click.argument('sources', nargs=-1)
@click.option(
'--extra',
'-x',
is_flag=True,
help=
'EXTRA-DATA: extract implicit types and predicates using basic inference rules. Note: by default ontospy extracts only classes/properties which are explictly declared.'
)
@click.option(
'--raw',
'-r',
is_flag=True,
help='RAW-DATA: print out the raw RDF data received.')
@click.option(
'--endpoint',
'-e',
is_flag=True,
help='ENDPOINT: the url passed is a sparql endpoint (beta).')
@click.pass_context
def ex(ctx, sources=None, endpoint=False, raw=False, extra=False):
"""EXAMINE: do a quick scan of an RDF source and print out a report.
"""
verbose = ctx.obj['VERBOSE']
sTime = ctx.obj['STIME']
print_opts = {
'labels': verbose,
'extra': extra,
}
if sources or (sources and endpoint):
action_analyze(sources, endpoint, print_opts, verbose, extra, raw)
eTime = time.time()
tTime = eTime - sTime
printDebug("\n-----------\n" + "Time: %0.2fs" % tTime, "comment")
else:
click.echo(ctx.get_help())
##
## GENDOCS COMMAND (wrapper around ontodocs)
##
......@@ -115,6 +152,13 @@ Ontospy is a command line inspector for RDF/OWL models. Use the --help option wi
help=
'OUTPUT-PATH: where to save the visualization files (default: home folder).'
)
@click.option(
'--extra',
'-x',
is_flag=True,
help=
'EXTRA-DATA: extract implicit types and predicates using basic inference rules. Note: by default ontospy extracts only classes/properties which are explictly declared.'
)
@click.option(
'--type',
help=
......@@ -144,16 +188,16 @@ Ontospy is a command line inspector for RDF/OWL models. Use the --help option wi
def gendocs(ctx,
source=None,
outputpath="",
extra=False,
lib=False,
type="",
title="",
theme="",
showthemes=False,
showtypes=False):
"""Generate documentation for an ontology in html or markdown format
"""GENDOCS: generate documentation in html or markdown format.
"""
verbose = ctx.obj['VERBOSE']
extra = ctx.obj['EXTRA']
sTime = ctx.obj['STIME']
print_opts = {
'labels': verbose,
......@@ -237,6 +281,13 @@ def gendocs(ctx,
help=
'SHOW: list all ontologies stored in the local library and prompt which one to open.'
)
@click.option(
'--extra',
'-x',
is_flag=True,
help=
'EXTRA-DATA: extract implicit types and predicates using basic inference rules. Note: by default ontospy extracts only classes/properties which are explictly declared.'
)
@click.option(
'--bootstrap',
is_flag=True,
......@@ -269,6 +320,7 @@ def gendocs(ctx,
@click.pass_context
def lib(ctx,
filepath=None,
extra=False,
bootstrap=False,
cache=False,
reveal=False,
......@@ -276,10 +328,9 @@ def lib(ctx,
save=False,
directory=False):
"""
Work with a local library of RDF models. If no option or argument is passed, by default the library contents are listed.
LIBRARY: work with a local library of RDF models.
"""
verbose = ctx.obj['VERBOSE']
extra = ctx.obj['EXTRA']
sTime = ctx.obj['STIME']
print_opts = {
'labels': verbose,
......@@ -361,39 +412,6 @@ def lib(ctx,
printDebug("Goodbye", "comment")
##
## SCAN COMMAND
##
@main_cli.command()
@click.argument('sources', nargs=-1)
@click.option(
'--endpoint',
'-e',
is_flag=True,
help='ENDPOINT: the source url passed is a sparql endpoint')
@click.pass_context
def scan(ctx, sources=None, endpoint=False):
"""Search an RDF source for ontology entities and print out a report.
"""
extra = ctx.obj['EXTRA']
verbose = ctx.obj['VERBOSE']
sTime = ctx.obj['STIME']
print_opts = {
'labels': verbose,
'extra': extra,
}
if sources or (sources and endpoint):
action_analyze(sources, endpoint, print_opts, verbose, extra)
eTime = time.time()
tTime = eTime - sTime
printDebug("\n-----------\n" + "Time: %0.2fs" % tTime, "comment")
else:
click.echo(ctx.get_help())
##
## SHELL COMMAN/'
##
......@@ -402,7 +420,7 @@ def scan(ctx, sources=None, endpoint=False):
@main_cli.command()
@click.argument('sources', nargs=-1)
def shell(sources=None):
"""Launch the ontospy repl, an interactive shell for querying ontologies. If an rdf source path is provided the repl is preloaded with it."
"""SHELL: launch ontospy's interactive mode. If an rdf source path is provided the shell is preloaded with it."
"""
from .extras.shell import launch_shell
launch_shell(sources)
......@@ -422,10 +440,9 @@ def shell(sources=None):
help='OUTPUT-FORMAT: the serialization format (default=turtle)')
# @click.argument('output_format', nargs=1)
@click.pass_context
def serial(ctx, source, output_format):
"""Serialize an RDF graph to a format of choice.
def ser(ctx, source, output_format):
"""SERIALIZE: tranform an RDF graph to a format of choice.
"""
extra = ctx.obj['EXTRA']
verbose = ctx.obj['VERBOSE']
sTime = ctx.obj['STIME']
print_opts = {
......@@ -442,7 +459,7 @@ def serial(ctx, source, output_format):
fg='red')
return
else:
action_transform(source, output_format, verbose)
action_serialize(source, output_format, verbose)
eTime = time.time()
tTime = eTime - sTime
printDebug(
......@@ -476,9 +493,8 @@ def utils(
jsonld=False,
discover=False,
):
"""Miscellaneous utilities.
"""UTILS: miscellaneous bits and pieces.
"""
extra = ctx.obj['EXTRA']
verbose = ctx.obj['VERBOSE']
sTime = ctx.obj['STIME']
print_opts = {
......
......@@ -65,7 +65,8 @@ def action_analyze(sources,
endpoint=None,
print_opts=False,
verbose=False,
extra=False):
extra=False,
raw=False):
"""
Load up a model into ontospy and analyze it
"""
......@@ -81,7 +82,12 @@ def action_analyze(sources,
hide_implicit_types = True
hide_implicit_preds = True
if endpoint:
if raw:
o = Ontospy(uri_or_path=sources, verbose=verbose, build_all=False)
s = o.serialize()
print(s)
return
elif endpoint:
g = Ontospy(
sparql_endpoint=sources[0],
verbose=verbose,
......@@ -115,7 +121,7 @@ def action_reveal_library():
subprocess.Popen(["xdg-open", path])
def action_transform(source, out_fmt="turtle", verbose=False):
def action_serialize(source, out_fmt="turtle", verbose=False):
"""
Util: render RDF into a different serialization
valid options are: xml, n3, turtle, nt, pretty-xml, json-ld
......@@ -249,7 +255,7 @@ def action_import(location, verbose=True):
if location.startswith("www."): #support for lazy people
location = "http://%s" % str(location)
if location.startswith("http"):
print("here")
# print("here")
headers = {'Accept': "application/rdf+xml"}
try:
# Py2
......
......@@ -544,7 +544,6 @@ def joinStringsInList(literalEntities, prefLanguage="en"):
return " - ".join([x for x in match])
def sortByNamespacePrefix(urisList, nsList):
"""
Given an ordered list of namespaces prefixes, order a list of uris based on that.
......@@ -693,7 +692,9 @@ def uri2niceString(aUri, namespaces=None):
if not namespaces:
namespaces = NAMESPACES_DEFAULT
if type(aUri) == rdflib.term.URIRef:
if not aUri:
stringa = ""
elif type(aUri) == rdflib.term.URIRef:
# we have a URI: try to create a qName
stringa = aUri.toPython()
for aNamespaceTuple in namespaces:
......
......@@ -552,7 +552,7 @@ class Shell(cmd.Cmd):
def _select_ontology(self, line):
"""try to select an ontology NP: the actual load from FS is in <_load_ontology> """
try:
var = int(line) # it's a string
var = int(line) # it's a string
if var in range(1, len(self.all_ontologies)+1):
self._load_ontology(self.all_ontologies[var-1])
except ValueError:
......@@ -900,7 +900,7 @@ class Shell(cmd.Cmd):
self._printPropertyDomainRange(False)
# self._printSourceCode(False)
if self.currentEntity and self.currentEntity['type'] == 'class':
self._print("Tip: type 'info inferred_usage' to show inherited properties")
self._print("Tip: type 'info inferred_usage' to show inherited properties\n----------------")
elif line[0] == "inferred_usage":
if self.currentEntity: # @todo only for classes?
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment