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:
- nltk - for reading a tree from a string and parsing it (as you've done).
- svgling - this library can read the output of the nltk tree and convert it into a svg.
- 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)