render_parse_tree_graphviz.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 Google Inc. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # ==============================================================================
  16. """Renders parse trees with Graphviz."""
  17. from __future__ import absolute_import
  18. from __future__ import division
  19. from __future__ import print_function
  20. import base64
  21. import warnings
  22. import pygraphviz
  23. def parse_tree_graph(sentence):
  24. """Constructs a parse tree graph.
  25. Args:
  26. sentence: syntaxnet.Sentence instance.
  27. Returns:
  28. HTML graph contents, as a string.
  29. """
  30. graph = pygraphviz.AGraph(directed=True, strict=False, rankdir="TB")
  31. for i, token in enumerate(sentence.token):
  32. node_id = "tok_{}".format(i)
  33. graph.add_node(node_id, label=token.word)
  34. if token.head >= 0:
  35. src_id = "tok_{}".format(token.head)
  36. graph.add_edge(
  37. src_id,
  38. node_id,
  39. label=token.label,
  40. key="parse_{}_{}".format(node_id, src_id))
  41. with warnings.catch_warnings():
  42. # Fontconfig spews some warnings, suppress them for now. (Especially because
  43. # they can clutter IPython notebooks).
  44. warnings.simplefilter("ignore")
  45. svg = graph.draw(format="svg", prog="dot")
  46. svg = unicode(svg, "utf-8")
  47. # For both inline and "new window" displays, we show the tokens with the
  48. # graph. (The sentence order of nodes is sometimes difficult to read.)
  49. image_and_text = u"<p><em>Text:</em> {}</p>{}".format(" ".join(
  50. token.word for token in sentence.token), svg)
  51. # We generate a base64 URI. This is not too big, but older browsers may not
  52. # handle it well.
  53. new_window_html = (u"<style type='text/css'>svg { max-width: 100%; }</style>"
  54. + image_and_text).encode("utf-8")
  55. as_uri = "data:text/html;charset=utf-8;base64,{}".format(
  56. base64.b64encode(new_window_html))
  57. return u"{}<p><a target='_blank' href='{}'>Open in new window</a></p>".format(
  58. image_and_text, as_uri)