iPython notebook plantuml extension
Asked Answered
D

4

8

How can we use plantuml UML tool in iPython notebook? It should helpful for us since UML figure is frequently used during paper work.

After some google from internet, I have found one excellent reference for Using Asymptote in iPython notebook, then I have created a plantuml extension for iPython notebook. Below is detail steps:

  • Start iPython notebook from my working directory.e.g:$HOME/workshop.

    # cd $HOME/workshop
    # ipython notebook --pylab inline
    
  • Create a extension script at $HOME/workshop.e.g:plantuml.py

    """
    An Plantuml extension for generating UML figures from within ipython notebook.
    """
    import os
    from IPython.core.magic import magics_class, cell_magic, Magics
    from IPython.display import Image, SVG
    
    @magics_class
    class Plantuml(Magics):
    
    @cell_magic
    def plantuml(self, line, cell):
        """Generate and display a figure using Plantuml.
        Usage:
            %java -jar plantuml.jar -tsvg filname
        """
        self.filename = line
        self.code = cell
    
        with open(self.filename + ".plt", "w") as file:
            file.write(self.code)
    
        os.system("java -jar plantuml.jar -tsvg %s.plt" % self.filename)
        return SVG(filename=self.filename+".svg")    
    
    def load_ipython_extension(ipython):
        ipython.register_magics(Plantuml)
    
  • Download plantuml.jar from official website to $HOME/workshop.

  • Create a new iPython notebook,run below cell to load extension and use the extension:

    %install_ext plantuml.py
    %reload_ext plantuml
    
  • Create a plantuml cell to test the result.

    %%plantuml figure1
    
    @startuml
    Alice -> Bob: Authentication Request
    Bob --> Alice: Authentication Response
    @enduml  
    

Then,everything from plantuml will work within iPython notebook.

Some questions are:

  • The error output of plantuml is NOT displayed in iPython notebook if any syntax wrong in plantuml code.it will be great if the SVG generation failure, then output the error text, othwise output the SVG file to notebook.
  • The extension is using SVG format, Not sure if it's possible to use PDF or PNG format.I wish to extension TiKz also but pdflatex always output pdf file format.I have to use a 3rd-party tool to covert it to SVG format firstly.it's a bit time consuming.
Denysedenzil answered 30/11, 2013 at 17:27 Comment(1)
The latest iPython has a document at IPython/html/static/custom/custom.cssDenysedenzil
C
6

Plantuml UML tool in iPython notebook is a great idea!

Instead of adding the jar, you can also use the web service. You can get the error message this way.

Based on the javascript API, I wrote a small python encoder to send strings to the plantUML server.

Now, the extension looks like this


import urllib
import plantumlencoder
from IPython.core.magic import magics_class, cell_magic, Magics
from IPython.display import Image, SVG

@magics_class
class Plantuml(Magics):

    @cell_magic
    def plantuml(self, line, cell):
        self.filename = line
        self.code = ""
        for line in cell.split('\n'):
            newline = line.strip()
            if newline:
                self.code += newline + '\n'

        uri = "http://www.plantuml.com/plantuml/svg/" + plantumlencoder.compress(self.code)

        urllib.urlretrieve(uri, self.filename)

        return SVG(filename=self.filename)    

def load_ipython_extension(ipython):
    ipython.register_magics(Plantuml)

To use other image formats you can change the URL, and the image code. For example : This extension produces png


import urllib
import plantumlencoder
from IPython.core.magic import magics_class, cell_magic, Magics
from IPython.display import Image, PNG

@magics_class
class Plantuml(Magics):

    @cell_magic
    def plantuml(self, line, cell):
        self.filename = line
        self.code = ""
        for line in cell.split('\n'):
            newline = line.strip()
            if newline:
                self.code += newline + '\n'

        uri = "http://www.plantuml.com/plantuml/png/" + plantumlencoder.compress(self.code)

        urllib.urlretrieve(uri, self.filename)

        return PNG(filename=self.filename)

def load_ipython_extension(ipython):
    ipython.register_magics(Plantuml)
Chaiken answered 11/8, 2014 at 3:49 Comment(3)
Good, but that means we always need network connection since everything is done in plantuml server!Denysedenzil
FYI. This is a great idea! Your github link gives a 404.Antifriction
@Denysedenzil Actually, if you're talking about plantuml.com services, you also can download, install and run the tools locally. github.com/plantuml/plantuml You probably even can install it through your package manager if you're on a Linux.Lacedaemonian
S
4

There is a PlantUML cell magic package. Please refer to iPlantUML@PyPi

After installation (pip install iplantuml) follow package introduction, you can create plantUML code in jupyterlab as follow:

Import package first,

import iplantuml

use cell magic:

%%plantuml 

@startuml
Alice -> Bob: Authentication Request
Bob --> Alice: Authentication Response
@enduml 

then show a diagram in cell output as:

enter image description here

Seibert answered 1/5, 2020 at 3:46 Comment(2)
doesn't wotk in jupyter-lab (Dogberry
@mystdeim it did work for me two weeks ago - doesnt work now. SyntaxError: invalid syntax on provably correct code. h8ful.Crownwork
T
1

Here is a solution using the -pipe option of plantuml:

from subprocess import run
from IPython.core.magic import register_cell_magic
from IPython.display import SVG

@register_cell_magic
def plantuml(line, code):
    cmd = ["plantuml", "-tsvg", "-pipe"]
    compl = run(cmd, input=code, text=True, capture_output=True)
    return SVG(compl.stdout)

This does not use the filesystem and can be defined in a cell. If you do not have a script for plantuml in your path you can define cmd as such:

jarpath = "path/to/plantuml.jar"
cmd = ["java", "-jar", jarpath, "-tsvg", "-pipe"]

After running the code above you can use the %%plantuml cell magic.

Teston answered 20/10, 2022 at 22:29 Comment(0)
L
0

you can use IJava and custom your java magic !

String[] mavenDependencies = {
    "net.sourceforge.plantuml:plantuml:8059"
};
getKernelInstance().getMavenResolver().addMavenDependencies(Arrays.asList(mavenDependencies));

import io.github.spencerpark.jupyter.kernel.magic.registry.LineMagic;
import io.github.spencerpark.jupyter.kernel.magic.registry.CellMagic;
import net.sourceforge.plantuml.SourceStringReader;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.FileFormat;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;

class CustomMagics {
    @CellMagic
    public void plantuml (List<String> args, String body) throws Exception {        
        SourceStringReader reader = new SourceStringReader(body);
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        String desc = reader.generateImage(outputStream, new FileFormatOption(FileFormat.SVG));
        outputStream.close();
        final String svg = new String(outputStream.toByteArray(), Charset.forName("UTF-8"));
        display(svg, "text/html");
    }
}
getKernelInstance().getMagics().registerMagics(new CustomMagics());
Labrie answered 7/9, 2023 at 12:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.