Skip to content
Snippets Groups Projects
Commit 082f2a97 authored by David Rouquet's avatar David Rouquet
Browse files

SVG pan zoom in notebooks

parent f11960b2
No related branches found
No related tags found
No related merge requests found
Pipeline #238 passed
%% Cell type:code id: tags:
``` python
import tempfile
import os
import base64
import re
import requests
from subprocess import Popen, PIPE, STDOUT
from IPython.display import SVG, display, HTML
from IPython.display import display, HTML
```
%% Cell type:code id: tags:
``` python
def unl2dot(text, path):
with tempfile.NamedTemporaryFile() as temp:
out_name = os.path.basename(temp.name)
out_dir = os.path.dirname(temp.name)
with tempfile.NamedTemporaryFile(mode="w") as in_file:
# Remove CRLF and flush output to avoid java errors
in_file.write(text.replace("\r\n", "\n"))
in_file.flush()
# Run java parser
cmd = ['java', '-jar', path,
'--input-file', in_file.name,
'--output-Dir', out_dir, '--output-file', out_name,
'--output-type', 'dot']
with Popen(cmd, stdout=PIPE, stderr=STDOUT) as p:
p.wait()
p.stdout.flush()
if p.returncode != 0:
print("Error in unl2rdf: \n\n"+p.stdout.read().decode())
print('UNL;')
print(text)
# generate dot output
fname = '{}/{}.dot'.format(out_dir, out_name)
cmd = ['dot', '-Tsvg', fname]
with Popen(cmd, stdout=PIPE, stderr=PIPE) as p:
p.wait()
if p.returncode != 0:
print("Error creating svg: \n\n"+p.stderr.read().decode())
print('UNL:')
print(text)
try:
with open(fname) as f:
print('DOT:')
print(f.read())
except FileNotFoundError:
pass
else:
svg = p.stdout.read().decode()
os.remove(fname)
return svg
return ""
def unl2dotWeb(unldata) :
data={'unl': unldata, 'outputs':['dot', 'svg']}
try:
r = requests.post('https://unl.demo.tetras-libre.fr/unl2rdf', data=data)
except Exception as e:
return 'Error calling https://unl.demo.tetras-libre.fr/unl2rdf : "{error}"'.format(error=e)
html=r.text
# On utilise une regex au lieu de parser le html car ce dernier est mal formé
regex = re.compile('<svg.*svg>',re.MULTILINE|re.DOTALL)
svg = regex.search(html).group()
return(svg)
def insert_in_html_template(svg):
# We first create the html code for the download link
b64 = base64.b64encode(svg.encode())
payload = b64.decode()
html_download = '<a href="data:image/svg+xml;base64,{payload}" download="{filename}">{title}</a>'
html_download = html_download.format(payload=payload,title='Télécharger le SVG : clic droit + "Enregistrer la cible du lien sous..."',filename="unl.svg")
html_template = '''
<body>
<script src="https://ariutta.github.io/svg-pan-zoom/dist/svg-pan-zoom.js"></script>
<div id="container" style="width:1030px; height: 570px; border:1px solid black; ">
<svg id="graph" xmlns="http://www.w3.org/2000/svg" style="display: inline; width: inherit; min-width: inherit; max-width: inherit; height: inherit; min-height: inherit; max-height: inherit; " viewBox="0 0 900 900">
##
</svg>
</div>
<script>
// Don't use window.onLoad like this in production, because it can only listen to one function.
window.onload = function() {
// Expose to window namespase for testing purposes
window.zoomGraph = svgPanZoom('#graph', {
zoomEnabled: true,
controlIconsEnabled: true,
fit: true,
center: true,
// viewportSelector: document.getElementById('graph').querySelector('#g4') // this option will make library to misbehave. Viewport should have no transform attribute
});
};
</script>
@@
</body>
'''
new_svg = svg.replace("<svg>","").replace("</svg>","")
return (html_template.replace("##",new_svg).replace("@@",html_download))
def displayUnl(unldata) :
# We generate protoSVG because whent there are several sentences,
# a string composed of several concatenated SVG is produced (not a valid SVG).
# We must then split the string to obtain several valid SVG to display.
sep = "[/S]\n"
unldataArray = [x+sep for x in unldata.split(sep)]
unldataArray.pop()
for unl in unldataArray :
regex = re.compile('\{org:..\}\n(.*)\n{\/org\}',re.MULTILINE|re.DOTALL)
text = regex.search(unl).group(1)
print("\n"+text+"\n")
# Keep one of the two lines below depending if you want to use a local jar or a webservice for unltools
try:
svg = unl2dotWeb(unl)
#svg = unl2dot(unl, "unl2rdf-app-1.0-SNAPSHOT-jar-with-dependencies.jar")
display(HTML(insert_in_html_template(svg)))
#return(insert_in_html_template(svg))
except Exception as e :
print(e)
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment