Commit 390069b0 authored by lambdamusic's avatar lambdamusic

ontodocs import

parent 7670ce7e
......@@ -364,7 +364,7 @@ if __name__ == '__main__':
@click.option(
'--showthemes', is_flag=True, help='Show the available CSS theme choices.')
@click.pass_context
def docs(ctx, source=None, outputpath="", title="", theme="",
def html(ctx, source=None, outputpath="", title="", theme="",
showthemes=False):
"""Generate documentation for an ontology in html or markdown format
"""
......@@ -374,14 +374,17 @@ def docs(ctx, source=None, outputpath="", title="", theme="",
'labels': verbose,
}
# from .ontodocs import *
from .ontodocs.builder import action_visualize
try:
import ontodocs
from ontodocs.core.builder import action_visualize
# check that we have the required dependencies
import django
except:
click.secho(
"WARNING: the ontodocs library is required for this functionality.",
"WARNING: this functionality requires the Django package and other extra dependecies.",
fg="red")
click.secho("Install with `pip install ontodocs -U`")
click.secho("Install with `pip install ontospy[HTML] -U`")
sys.exit(0)
if showthemes:
......
......@@ -145,7 +145,7 @@ def action_listlocal(all_details=True):
"------------------\nSelect a model by typing its number: (enter=quit)",
"important")
var = input()
if var == "":
if var == "" or var == "q":
return None
else:
try:
......
#!/usr/bin/python
# -*- coding: utf-8 -*-
VISUALIZATIONS_LIST = {
"Visualizations":
[{
"ID": "html-simple",
"Title": "Html: single-page",
"Description": "@todo",
} , {
"ID": "html-complex",
"Title": "Html: multi-page",
"Description": "@todo",
} , {
"ID": "markdown",
"Title": "Markdown: multi-page",
"Description": "@todo",
} , {
"ID": "d3-tree",
"Title": "D3 Dendogram",
"Description": "@todo",
}
]
}
BOOTSWATCH_THEMES = ['cerulean' , 'flatly' , 'lumen' , 'sandstone' , 'spacelab' , 'yeti' , 'cosmo' , 'darkly' , 'paper' , 'simplex' , 'superhero' , 'readable' , 'slate' , 'united']
BOOTSWATCH_THEME_DEFAULT = "simplex"
# 'cyborg' , 'journal'
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
\ No newline at end of file
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
#
#
# VIZ MODULE : util to visualize an ontology as html or similar
#
#
import click
import os
from shutil import copyfile
# Fix Python 2.x.
try:
input = raw_input
except NameError:
pass
# django loading requires different steps based on version
# https://docs.djangoproject.com/en/dev/releases/1.7/#standalone-scripts
import django
# http://stackoverflow.com/questions/1714027/version-number-comparison
from distutils.version import StrictVersion
from ..core import actions as ontospy_actions
from ..core import manager as ontospy_manager
from ..core.utils import *
from .. import *
_dirname, _filename = os.path.split(os.path.abspath(__file__))
ONTODOCS_VIZ_TEMPLATES = _dirname + "/media/templates/"
ONTODOCS_VIZ_STATIC = _dirname + "/media/static/"
if StrictVersion(django.get_version()) > StrictVersion('1.7'):
from django.conf import settings
from django.template import Context, Template
settings.configure()
django.setup()
settings.TEMPLATES = [
{
'BACKEND':
'django.template.backends.django.DjangoTemplates',
'DIRS': [
# insert your TEMPLATE_DIRS here
ONTODOCS_VIZ_TEMPLATES + "html-single",
ONTODOCS_VIZ_TEMPLATES + "html-multi",
ONTODOCS_VIZ_TEMPLATES + "markdown",
ONTODOCS_VIZ_TEMPLATES + "d3",
ONTODOCS_VIZ_TEMPLATES + "misc",
],
'APP_DIRS':
True,
'OPTIONS': {
'context_processors': [
# Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
# list if you haven't customized them:
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
else:
from django.conf import settings
from django.template import Context, Template
settings.configure()
try:
from .CONFIG import VISUALIZATIONS_LIST, BOOTSWATCH_THEMES, BOOTSWATCH_THEME_DEFAULT
VISUALIZATIONS_LIST = VISUALIZATIONS_LIST['Visualizations']
except: # Mother of all exceptions
click.secho("Visualizations configuration file not found.", fg="red")
raise
def show_themes():
for t in BOOTSWATCH_THEMES:
printDebug(t, "green")
def random_theme():
return random.choice(BOOTSWATCH_THEMES)
def validate_theme(theme_try, default=BOOTSWATCH_THEME_DEFAULT):
# print theme_try
if not theme_try:
return default
if theme_try in BOOTSWATCH_THEMES:
return theme_try
else:
printDebug("Warning: theme not found", "red")
return default
def ask_visualization():
"""
ask user which viz output to use
"""
printDebug(
"Please choose an output format for the ontology visualization: (q=quit)\n",
"important")
while True:
text = ""
for viz in VISUALIZATIONS_LIST:
text += "%d) %s\n" % (VISUALIZATIONS_LIST.index(viz) + 1,
viz['Title'])
var = input(text + ">")
if var == "q":
return ""
else:
try:
n = int(var) - 1
test = VISUALIZATIONS_LIST[
n] # throw exception if number wrong
return n
except:
printDebug("Invalid selection. Please try again.", "red")
continue
# MAIN METHOD
def action_visualize(args,
fromshell=False,
path=None,
title="",
theme="",
verbose=False):
"""
export model into another format eg html, d3 etc...
<fromshell> : the local name is being passed from ontospy shell
"""
# get argument
if not (args):
ontouri = ontospy_actions.action_listlocal(all_details=False)
if ontouri:
islocal = True
else:
raise SystemExit(1)
elif fromshell:
ontouri = args
islocal = True
else:
ontouri = args[0]
islocal = False
# select a visualization
viztype = ask_visualization()
if viztype == "":
return None
# raise SystemExit, 1
# 2017-01-23: bypass pickled stuff as it has wrong counts etc..
USE_CACHE = False
# get ontospy graph
if islocal and USE_CACHE:
g = get_pickled_ontology(ontouri)
if not g:
g = do_pickle_ontology(ontouri)
else:
printDebug("Loading graph...", dim=True)
if islocal:
g = Ontospy(
os.path.join(ontospy_manager.get_home_location(), ontouri),
verbose=verbose)
else:
g = Ontospy(ontouri, verbose=verbose)
# put in home folder by default: <ontouri>/<viztype>/files..
if not path:
from os.path import expanduser
home = expanduser("~")
onto_path = slugify(unicode(ontouri))
viz_path = slugify(unicode(VISUALIZATIONS_LIST[viztype]['Title']))
path = os.path.join(home, "ontospy-viz/" + onto_path + "/" + viz_path)
if not os.path.exists(path):
os.makedirs(path)
# url = build_viz(ontouri, g, viztype, path)
printDebug("Building visualization...", dim=True)
url = build_visualization(ontouri, g, viztype, path, title, theme)
return url
# ===========
# VIZ SELECTION FUNCTION
# ===========
def build_visualization(ontouri, g, viz_index, path=None, title="", theme=""):
"""
2017-01-20: new verion, less clever but also simpler
:param g:
:param viz_index:
:param main_entity:
:return:
"""
this_viz = VISUALIZATIONS_LIST[viz_index]
if this_viz['ID'] == "html-simple":
from ..viz.viz_html_single import HTMLVisualizer
v = HTMLVisualizer(g, title)
elif this_viz['ID'] == "html-complex":
from ..viz.viz_html_multi import KompleteViz
v = KompleteViz(g, title, theme)
elif this_viz['ID'] == "markdown":
from ..viz.viz_markdown import MarkdownViz
v = MarkdownViz(g, title)
elif this_viz['ID'] == "d3-tree":
from ..viz.viz_d3tree import D3TreeViz
v = D3TreeViz(g, title)
else:
return False
url = v.build(path)
return url
# ?LEGACY
def saveVizGithub(contents, ontouri):
"""
DEPRECATED on 2016-11-16
Was working but had a dependecies on package 'uritemplate.py' which caused problems at installation time
"""
title = "OntoSpy: ontology export"
readme = """This ontology documentation was automatically generated with OntoSpy (https://github.com/lambdamusic/OntoSpy).
The graph URI is: %s""" % str(ontouri)
files = {
'index.html': {
'content': contents
},
'README.txt': {
'content': readme
},
'LICENSE.txt': {
'content':
"""The MIT License (MIT)
Copyright (c) 2016 OntoSpy project [http://ontospy.readthedocs.org/]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE."""
}
}
urls = save_anonymous_gist(title, files)
return urls
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<!-- {# <link type="text/css" rel="stylesheet" href="style.css"/> #} -->
<style type="text/css">
text {
font-size: 11px;
pointer-events: none;
}
text.parent {
fill: #1f77b4;
}
circle {
fill: #ccc;
stroke: #999;
pointer-events: all;
}
circle.parent {
fill: #1f77b4;
fill-opacity: .1;
stroke: steelblue;
}
circle.parent:hover {
stroke: #ff7f0e;
stroke-width: .5px;
}
circle.child {
pointer-events: none;
}
</style>
</head>
<body>
<h2>
Flare code size<br>
circle packing
</h2>
<script type="text/javascript" src="d3.v3.min.js"></script>
<script type="text/javascript">
var w = 1280,
h = 800,
r = 720,
x = d3.scale.linear().range([0, r]),
y = d3.scale.linear().range([0, r]),
node,
root;
var pack = d3.layout.pack()
.size([r, r])
.value(function(d) { return d.size; })
var vis = d3.select("body").insert("svg:svg", "h2")
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(" + (w - r) / 2 + "," + (h - r) / 2 + ")");
d3.json("flare.json", function(data) {
node = root = data;
var nodes = pack.nodes(root);
vis.selectAll("circle")
.data(nodes)
.enter().append("svg:circle")
.attr("class", function(d) { return d.children ? "parent" : "child"; })
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", function(d) { return d.r; })
.on("click", function(d) { return zoom(node == d ? root : d); });
vis.selectAll("text")
.data(nodes)
.enter().append("svg:text")
.attr("class", function(d) { return d.children ? "parent" : "child"; })
.attr("x", function(d) { return d.x; })
.attr("y", function(d) { return d.y; })
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.style("opacity", function(d) { return d.r > 20 ? 1 : 0; })
.text(function(d) { return d.name; });
d3.select(window).on("click", function() { zoom(root); });
});
function zoom(d, i) {
var k = r / d.r / 2;
x.domain([d.x - d.r, d.x + d.r]);
y.domain([d.y - d.r, d.y + d.r]);
var t = vis.transition()
.duration(d3.event.altKey ? 7500 : 750);
t.selectAll("circle")
.attr("cx", function(d) { return x(d.x); })
.attr("cy", function(d) { return y(d.y); })
.attr("r", function(d) { return k * d.r; });
t.selectAll("text")
.attr("x", function(d) { return x(d.x); })
.attr("y", function(d) { return y(d.y); })
.style("opacity", function(d) { return k * d.r > 20 ? 1 : 0; });
node = d;
d3.event.stopPropagation();
}
</script>
</body>
</html>
This diff is collapsed.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:foaf="http://xmlns.com/foaf/0.1/"
xmlns:vs="http://www.w3.org/2003/06/sw-vocab-status/ns#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:owl="http://www.w3.org/2002/07/owl#"
xmlns:dct="http://purl.org/dc/terms/"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<title>{{ontology.uri}}</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
{# trick to be able to load the json data cross-domain... #}
{# <script type="text/javascript" src="{{STATIC_PATH}}sample.js"></script> #}
<script type="text/javascript">
var JSON_DATA = {{JSON_DATA|safe}};
</script>
<style type="text/css" media="screen">
/* tree.css contents */
body {
/* overflow: hidden;*/
margin-left: 6em;
margin-right: 12em;
font-size: 14px;
font-family: "Helvetica Neue", Helvetica;
}
h1, h2, h3, h4, h5, h6 { text-align: left }
/* background should be transparent, but WebTV has a bug */
h1, h2, h3, h4, h5 { color: #000000; background: white }
h2 { font: 140% sans-serif }
h3 { font: 120% sans-serif }
h4 { font: bold 100% sans-serif }
h5 { font: italic 100% sans-serif }
h6 { font: small-caps 100% sans-serif }
#chart, #header, #footer {
position: absolute;
top: 0;
}
#header, #footer {
z-index: 1;
display: block;
font-size: 36px;
font-weight: 300;
text-shadow: 0 1px 0 #fff;
}
#header.inverted, #footer.inverted {
color: #fff;
text-shadow: 0 1px 4px #000;
}
#header {
top: 80px;
left: 140px;
width: 1000px;