4

Taken from Saving nltk drawn parse tree to image file

I would like to know how I can save an image when using a headless VM/server? Right now I'm getting:

_tkinter.TclError: no display name and no $DISPLAY environment variable

from nltk import Tree
from nltk.draw.util import CanvasFrame
from nltk.draw import TreeWidget

cf = CanvasFrame()
t = Tree.fromstring('(S (NP this tree) (VP (V is) (AdjP pretty)))')
tc = TreeWidget(cf.canvas(),t)
cf.add_widget(tc,10,10) # (10,10) offsets
cf.print_to_file('tree.ps')
cf.destroy()
Community
  • 1
  • 1
Jim Factor
  • 1,465
  • 1
  • 15
  • 24

1 Answers1

0

So after a lot of exploring and experimenting with tons of libraries and approaches of getting the nltk parse tree from the string to a final image, the following is what worked for me:

Dependencies to be installed:

  1. nltk - for reading a tree from a string and parsing it (as you've done).
  2. svgling - this library can read the output of the nltk tree and convert it into a svg.
  3. cairosvg - this library reads an svg and can convert it into anything from png, pdf etc. it doesn't depend on tcl/tkinter so no issue with a headless server!

Code with a sample tree:

import svgling
import cairosvg
from nltk.tree import Tree

# converts any nltk tree object to a svg
def tree2svg(t):
    img = svgling.draw_tree(t)
    svg_data = img.get_svg()
    return svg_data

# read from a string and parse the tree using nltk
t = Tree.fromstring('(ROOT (S (NP (DT The) (NN debate)) (VP (VBN continued) (PP (IN till) (NP (NN night)))) (. .)))')
# convert tree to svg
sv = tree2svg(t)
# write the svg as an image
cairosvg.svg2png(sv.tostring(), write_to='image.png')

The above piece of code worked flawlessly on a ubuntu wsl inside windows 10 so it should work for any server too (as I was facing exactly the same issue that you were)

FossArduino
  • 161
  • 2
  • 2
  • 11