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

allow svg pan-zoom in notebooks

parent 44f38dd6
No related branches found
No related tags found
No related merge requests found
Pipeline #237 passed
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import tempfile import tempfile
import os import os
import re import re
import requests import requests
from subprocess import Popen, PIPE, STDOUT from subprocess import Popen, PIPE, STDOUT
from IPython.display import SVG, display, HTML from IPython.display import SVG, display, HTML
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def unl2dot(text, path): def unl2dot(text, path):
with tempfile.NamedTemporaryFile() as temp: with tempfile.NamedTemporaryFile() as temp:
out_name = os.path.basename(temp.name) out_name = os.path.basename(temp.name)
out_dir = os.path.dirname(temp.name) out_dir = os.path.dirname(temp.name)
with tempfile.NamedTemporaryFile(mode="w") as in_file: with tempfile.NamedTemporaryFile(mode="w") as in_file:
# Remove CRLF and flush output to avoid java errors # Remove CRLF and flush output to avoid java errors
in_file.write(text.replace("\r\n", "\n")) in_file.write(text.replace("\r\n", "\n"))
in_file.flush() in_file.flush()
# Run java parser # Run java parser
cmd = ['java', '-jar', path, cmd = ['java', '-jar', path,
'--input-file', in_file.name, '--input-file', in_file.name,
'--output-Dir', out_dir, '--output-file', out_name, '--output-Dir', out_dir, '--output-file', out_name,
'--output-type', 'dot'] '--output-type', 'dot']
with Popen(cmd, stdout=PIPE, stderr=STDOUT) as p: with Popen(cmd, stdout=PIPE, stderr=STDOUT) as p:
p.wait() p.wait()
p.stdout.flush() p.stdout.flush()
if p.returncode != 0: if p.returncode != 0:
print("Error in unl2rdf: \n\n"+p.stdout.read().decode()) print("Error in unl2rdf: \n\n"+p.stdout.read().decode())
print('UNL;') print('UNL;')
print(text) print(text)
# generate dot output # generate dot output
fname = '{}/{}.dot'.format(out_dir, out_name) fname = '{}/{}.dot'.format(out_dir, out_name)
cmd = ['dot', '-Tsvg', fname] cmd = ['dot', '-Tsvg', fname]
with Popen(cmd, stdout=PIPE, stderr=PIPE) as p: with Popen(cmd, stdout=PIPE, stderr=PIPE) as p:
p.wait() p.wait()
if p.returncode != 0: if p.returncode != 0:
print("Error creating svg: \n\n"+p.stderr.read().decode()) print("Error creating svg: \n\n"+p.stderr.read().decode())
print('UNL:') print('UNL:')
print(text) print(text)
try: try:
with open(fname) as f: with open(fname) as f:
print('DOT:') print('DOT:')
print(f.read()) print(f.read())
except FileNotFoundError: except FileNotFoundError:
pass pass
else: else:
svg = p.stdout.read().decode() svg = p.stdout.read().decode()
os.remove(fname) os.remove(fname)
return svg return svg
return "" return ""
def unl2dotWeb(unldata) : def unl2dotWeb(unldata) :
data={'unl': unldata, 'outputs':['dot', 'svg']} data={'unl': unldata, 'outputs':['dot', 'svg']}
try: try:
r = requests.post('https://unl.demo.tetras-libre.fr/unl2rdf', data=data) r = requests.post('https://unl.demo.tetras-libre.fr/unl2rdf', data=data)
except Exception as e: except Exception as e:
return 'Error calling https://unl.demo.tetras-libre.fr/unl2rdf : "{error}"'.format(error=e) return 'Error calling https://unl.demo.tetras-libre.fr/unl2rdf : "{error}"'.format(error=e)
html=r.text html=r.text
# On utilise une regex au lieu de parser le html car ce dernier est mal formé # 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) regex = re.compile('<svg.*svg>',re.MULTILINE|re.DOTALL)
svg = regex.search(html).group() svg = regex.search(html).group()
return(svg) return(svg)
def svg_to_fixed_width_html_image(svg, width="100%"): def insert_in_html_template(svg):
html_template='<img width="{}">{}</img>' # We first create the html code for the download link
text = html_template.format(width, svg) b64 = base64.b64encode(svg.encode())
return HTML(text) 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) : def displayUnl(unldata) :
# We generate protoSVG because whent there are several sentences, # We generate protoSVG because whent there are several sentences,
# a string composed of several concatenated SVG is produced (not a valid SVG). # 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. # We must then split the string to obtain several valid SVG to display.
sep = "[/S]\n" sep = "[/S]\n"
unldataArray = [x+sep for x in unldata.split(sep)] unldataArray = [x+sep for x in unldata.split(sep)]
unldataArray.pop() unldataArray.pop()
for unl in unldataArray : for unl in unldataArray :
regex = re.compile('\{org:..\}\n(.*)\n{\/org\}',re.MULTILINE|re.DOTALL) regex = re.compile('\{org:..\}\n(.*)\n{\/org\}',re.MULTILINE|re.DOTALL)
text = regex.search(unl).group(1) text = regex.search(unl).group(1)
print("\n"+text+"\n") 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 # Keep one of the two lines below depending if you want to use a local jar or a webservice for unltools
try: try:
#svg = unl2dotWeb(unl) svg = unl2dotWeb(unl)
svg = unl2dot(unl, "unl2rdf-app-1.0-SNAPSHOT-jar-with-dependencies.jar") #svg = unl2dot(unl, "unl2rdf-app-1.0-SNAPSHOT-jar-with-dependencies.jar")
display(svg_to_fixed_width_html_image(svg)) display(HTML(insert_in_html_template(svg)))
#return(insert_in_html_template(svg))
except Exception as e : except Exception as e :
print(e) print(e)
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment