Skip to main content

Sphinx extension to render the image by script or command

Project description

A sphinx extension to render the image/figure generated by the command body.

author:

“Yongping Guo”<guoyoooping@163.com>

1. Installing and setup

pip install sphinxcontrib-cmd2img

And just add sphinxcontrib.cmd2img to the list of extensions in the conf.py file. For example:

extensions = ['sphinxcontrib.cmd2img']

2. Introduction and examples

In rst we we use image and figure directive to render image/figure in the target html document, which give us much convenience. In fact we could rending more things than that.

Sometime some command would convert or generate a image, we would like to render it efficiently and directly, for example:

2.1 ditaa example

ditaa is a small command-line utility that can convert diagrams drawn using ascii art (‘drawings’ that contain characters that resemble lines like | / - ), into proper bitmap graphics. We could use the following directive to render the image generated by ditaa:

.. cmd2img:: ditaa

      +--------+   +-------+    +-------+
      |        | --+ ditaa +--> |       |
      |  Text  |   +-------+    |diagram|
      |Document|   |!magic!|    |       |
      |     {d}|   |       |    |       |
      +---+----+   +-------+    +-------+
          :                         ^
          |       Lots of work      |
          +-------------------------+

Or use the following directive to render it as a figure, for a figure, we can add a caption, to render it as .svg file, we add –svg in the command line:

.. cmd2fig:: ditaa --svg
   :caption: figure 1. An example to use ditaa to render a figure

      +--------+   +-------+    +-------+
      |        | --+ ditaa +--> |       |
      |  Text  |   +-------+    |diagram|
      |Document|   |!magic!|    |       |
      |     {d}|   |       |    |       |
      +---+----+   +-------+    +-------+
          :                         ^
          |       Lots of work      |
          +-------------------------+

After conversion using ditaa, the above file becomes:

http://ditaa.sourceforge.net/images/first.png

2.2 gnuplot example

Another example is gnuplot. Since the output result is embedded in the script, we use “:image: transparent.2.png” to assign the output file explicitly, cmd2fig seems much like cmd2img, it has more options, for example it can assign the image name in the document:

.. cmd2fig:: gnuplot
    :image: transparent.2.png
    :caption: figure 2. illustration for command option.

    set terminal pngcairo  transparent enhanced font "arial,8" fontscale 1.0 size 512, 280
    set output 'transparent.2.png'
    set style fill transparent solid 0.5 noborder
    set style function filledcurves y1=0

    Gauss(x,mu,sigma) = 1./(sigma*sqrt(2*pi)) * exp( -(x-mu)**2 / (2*sigma**2) )
    d1(x) = Gauss(x, 0.5, 0.5)
    d2(x) = Gauss(x,  2.,  1.)
    d3(x) = Gauss(x, -1.,  2.)

    set xrange [-5:5]
    set yrange [0:1]
    set key title "Gaussian Distribution"
    set key top left Left reverse samplen 1
    set title "Transparent filled curves"
    plot d1(x) fs solid 1.0 lc rgb "forest-green" title "μ =  0.5 σ = 0.5", \
         d2(x) lc rgb "gold" title "μ =  2.0 σ = 1.0", \
         d3(x) lc rgb "dark-violet" title "μ = -1.0 σ = 2.0"

After conversion using gnuplot, the above file becomes:

http://gnuplot.sourceforge.net/demo_5.2/transparent.2.png

2.3 python example

Another example is gnuplot. Since the output result is embedded in the script, we use “:image: sphx_glr_artists_001.2.png” to assign the output file explicitly:

.. cmd2img:: python3
    :image: sphx_glr_artists_001.png
    :caption: 例子

    import numpy as np
    import matplotlib.pyplot as plt

    fig = plt.figure()
    fig.subplots_adjust(top=0.8)
    ax1 = fig.add_subplot(211)
    ax1.set_ylabel('volts')
    ax1.set_title('a sine wave')

    t = np.arange(0.0, 1.0, 0.01)
    s = np.sin(2*np.pi*t)
    line, = ax1.plot(t, s, color='blue', lw=2)

    # Fixing random state for reproducibility
    np.random.seed(19680801)

    ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3])
    n, bins, patches = ax2.hist(np.random.randn(1000), 50,
                                facecolor='yellow', edgecolor='yellow')
    ax2.set_xlabel('time (s)')
    plt.savefig("sphx_glr_artists_001.png")

After conversion using python3, the above file becomes:

https://matplotlib.org/3.2.1/_images/sphx_glr_artists_001.png

2.4 convert example

Another example is convert. Since the output result is embedded in the script, we use “:image: properity_option_append.png” to assign the output file explicitly:

.. cmd2img:: convert rose:  -set option:myinfo 'I love IM!'  label:'== %[myinfo] ==' -gravity center -append properity_option_append.gif
    :image: properity_option_append.png

After conversion using convert, the above file becomes:

http://www.imagemagick.org/Usage/basics/properity_option_append.gif

2.5 dot example

Another example is dot, since we want to generate png image, we add the option in the command, it’s dot’s own option:

.. cmd2img:: dot -Tpng

    digraph G {

            subgraph cluster_0 {
                    style=filled;
                    color=lightgrey;
                    node [style=filled,color=white];
                    a0 -> a1 -> a2 -> a3;
                    label = "process #1";
            }

            subgraph cluster_1 {
                    node [style=filled];
                    b0 -> b1 -> b2 -> b3;
                    label = "process #2";
                    color=blue
            }
            start -> a0;
            start -> b0;
            a1 -> b3;
            b2 -> a3;
            a3 -> a0;
            a3 -> end;
            b3 -> end;

            start [shape=Mdiamond];
            end [shape=Msquare];
    }

After conversion using dot, the above file becomes:

https://graphviz.gitlab.io/_pages/Gallery/directed/cluster.png

3 Options

sphinxcontrib-cmd2img provide some options for easy use.

3.1 command options

For command options, you should add it right after the command, for example:

.. cmd2fig:: ditaa --no-antialias
   :caption: figure 2. illustration for command option.

    +--------+   +-------+    +-------+
    |        | --+ ditaa +--> |       |
    |  Text  |   +-------+    |diagram|
    |Document|   |!magic!|    |       |
    |     {d}|   |       |    |       |
    +---+----+   +-------+    +-------+
        :                         ^
        |       Lots of work      |
        +-------------------------+

3.2 sphinxcontrib-cmd2img options

  • image:

    For those command whose the output name is embeded in the body, Users should copy the name here.

  • show_source:

    for text generated iamge, if the source code is shown.

  • watermark:

    Add water mark in the image

  • gravity:

    watermark gravity, see detail imagematick command convert -draw

  • location:

    watermark location, see detail imagematick command convert -draw

  • fill:

    watermark contention, see detail imagematick command convert -draw

  • pointsize:

    watermark pointsize, see detail imagematick command convert -draw

  • font:

    watermark font, see detail imagematick command convert -draw

For example:

.. cmd2fig:: gnuplot
    :caption: 在plot 命令里指定范围
    :image: gnuplot_test.png
    :width: 600

    set output 'gnuplot_test.png'
    set terminal pngcairo
    plot [-5:5] (sin(1/x) - cos(x))*erfc(x)

5. License

GPLv3

6. Changelog

0.1 Initial upload. 0.2 Correct minor typo 1.0 Upgrade to 1.0, bug fix: If there is change of the script, it doesn’t generate a new image. 1.0.2 Bug fix: When copy file error, shouldn’t break the following process. 1.0.3 Bug fix: dot doesn’t work now fix it.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sphinxcontrib-cmd2img-1.0.3.tar.gz (11.9 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page