Commit 038ff555 by Steven Xu

use png instead of pdf due to it's wider support (in the qt console and in firefox)

parent 203ac186
...@@ -689,13 +689,19 @@ class Tree(list): ...@@ -689,13 +689,19 @@ class Tree(list):
childstr = ", ".join(unicode_repr(c) for c in self) childstr = ", ".join(unicode_repr(c) for c in self)
return '%s(%s, [%s])' % (type(self).__name__, unicode_repr(self._label), childstr) return '%s(%s, [%s])' % (type(self).__name__, unicode_repr(self._label), childstr)
def _repr_pdf_(self): def _repr_png_(self):
"""
Draws and outputs in PNG for ipython.
PNG is used instead of PDF, since it can be displayed in the qt console and
has wider browser support.
"""
import os import os
import base64 import base64
import subprocess import subprocess
import tempfile import tempfile
from nltk.draw.tree import tree_to_treesegment from nltk.draw.tree import tree_to_treesegment
from nltk.draw.util import CanvasFrame from nltk.draw.util import CanvasFrame
from nltk.internals import find_binary
_canvas_frame = CanvasFrame() _canvas_frame = CanvasFrame()
widget = tree_to_treesegment(_canvas_frame.canvas(), self) widget = tree_to_treesegment(_canvas_frame.canvas(), self)
_canvas_frame.add_widget(widget) _canvas_frame.add_widget(widget)
...@@ -703,15 +709,18 @@ class Tree(list): ...@@ -703,15 +709,18 @@ class Tree(list):
# print_to_file uses scrollregion to set the width and height of the pdf. # print_to_file uses scrollregion to set the width and height of the pdf.
_canvas_frame.canvas()['scrollregion'] = (0, 0, w, h) _canvas_frame.canvas()['scrollregion'] = (0, 0, w, h)
with tempfile.NamedTemporaryFile() as file: with tempfile.NamedTemporaryFile() as file:
ps_path = '{0:}.ps'.format(file.name) in_path = '{0:}.ps'.format(file.name)
pdf_path = '{0:}.pdf'.format(file.name) out_path = '{0:}.png'.format(file.name)
_canvas_frame.print_to_file(ps_path) _canvas_frame.print_to_file(in_path)
_canvas_frame.destroy_widget(widget) _canvas_frame.destroy_widget(widget)
subprocess.call(['epstopdf', ps_path], shell=True) subprocess.call([find_binary('gs', binary_names=['gswin32c.exe', 'gswin64c.exe'], env_vars=['PATH'], verbose=False)] +
with open(pdf_path, 'rb') as sr: '-q -dEPSCrop -sDEVICE=png16m -r90 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -dSAFER -dBATCH -dNOPAUSE -sOutputFile={0:} {1:}'
.format(out_path, in_path).split(),
shell=True)
with open(out_path, 'rb') as sr:
res = sr.read() res = sr.read()
os.remove(ps_path) os.remove(in_path)
os.remove(pdf_path) os.remove(out_path)
return base64.b64encode(res).decode() return base64.b64encode(res).decode()
def __str__(self): def __str__(self):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment