Esempio n. 1
0
 def test_embed_google_web_font(self):
     dwg = Drawing()
     dwg.embed_google_web_font(
         name="Indie Flower",
         uri="http://fonts.googleapis.com/css?family=Indie+Flower")
     style = dwg.defs.elements[0]
     self.assertEqual(style.elementname, 'style')
Esempio n. 2
0
 def test_empty_drawing(self):
     dwg = Drawing(profile="tiny")
     result = dwg.tostring()
     self.assertEqual(result, '<svg baseProfile="tiny" height="100%" version="1.2" '
                              'width="100%" xmlns="http://www.w3.org/2000/svg" '
                              'xmlns:ev="http://www.w3.org/2001/xml-events" '
                              'xmlns:xlink="http://www.w3.org/1999/xlink"><defs /></svg>')
Esempio n. 3
0
    def render_nlpgraphics(renderer,
                           filtered,
                           filepath: str = None,
                           output_type: str = 'SVG'):
        """Render an NLPInstance into the supported formats.

        Args:
            renderer (SingleSentenceRenderer or AlignmentRenderer): The renderer object.
            filtered (NLPInstance): The filtered NLPInstane to be rendered.
            filepath (str): The path of the outputfile.
            output_type (str): The type of the output format.

        Returns: The bytesting of the rendered object if needed.
        """
        svg_scene = Drawing(size=('100%', '100%'))  # default: '100%', '100%'

        dim = renderer.render(filtered, svg_scene)

        # Set the actual computed dimension without rerendering
        svg_scene.attribs['width'] = dim[0]
        svg_scene.attribs['height'] = dim[1]

        svg_bytes = svg_scene.tostring().encode('UTF-8')

        if filepath is not None and output_type == 'SVG':
            svg_scene.saveas(filepath)
        elif filepath is None and output_type == 'SVG':
            return svg_bytes
        elif output_type == 'PS':
            cairosvg.svg2ps(bytestring=svg_bytes, write_to=filepath)
        elif output_type == 'PDF':
            cairosvg.svg2pdf(bytestring=svg_bytes, write_to=filepath)
        else:
            raise ValueError(
                '{0} not a supported filetype!'.format(output_type))
Esempio n. 4
0
 def test_save_as(self):
     fn = 'test_drawing.svg'
     if os.path.exists(fn):
         os.remove(fn)
     dwg = Drawing()
     dwg.saveas(fn)
     self.assertTrue(os.path.exists(fn))
     os.remove(fn)
Esempio n. 5
0
 def test_save_as(self):
     fn = Path('test_drawing.svg')
     if fn.exists():
         fn.unlink()
     dwg = Drawing()
     dwg.saveas(str(fn))
     self.assertTrue(fn.exists())
     fn.unlink()
Esempio n. 6
0
def get_4cat_canvas(path, width, height, header=None, footer="made with 4cat - 4cat.oilab.nl", fontsize_normal=None,
					fontsize_small=None, fontsize_large=None):
	"""
	Get a standard SVG canvas to draw 4CAT graphs to

	Adds a border, footer, header, and some basic text styling

	:param path:  The path where the SVG graph will be saved
	:param width:  Width of the canvas
	:param height:  Height of the canvas
	:param header:  Header, if necessary to draw
	:param footer:  Footer text, if necessary to draw. Defaults to shameless
	4CAT advertisement.
	:param fontsize_normal:  Font size of normal text
	:param fontsize_small:  Font size of small text (e.g. footer)
	:param fontsize_large:  Font size of large text (e.g. header)
	:return SVG:  SVG canvas (via svgwrite) that can be drawn to
	"""
	from svgwrite.container import SVG
	from svgwrite.drawing import Drawing
	from svgwrite.shapes import Rect
	from svgwrite.text import Text

	if fontsize_normal is None:
		fontsize_normal = width / 75

	if fontsize_small is None:
		fontsize_small = width / 100

	if fontsize_large is None:
		fontsize_large = width / 50

	# instantiate with border and white background
	canvas = Drawing(str(path), size=(width, height), style="font-family:monospace;font-size:%ipx" % fontsize_normal)
	canvas.add(Rect(insert=(0, 0), size=(width, height), stroke="#000", stroke_width=2, fill="#FFF"))

	# header
	if header:
		header_shape = SVG(insert=(0, 0), size=("100%", fontsize_large * 2))
		header_shape.add(Rect(insert=(0, 0), size=("100%", "100%"), fill="#000"))
		header_shape.add(
			Text(insert=("50%", "50%"), text=header, dominant_baseline="middle", text_anchor="middle", fill="#FFF",
				 style="font-size:%ipx" % fontsize_large))
		canvas.add(header_shape)

	# footer (i.e. 4cat banner)
	if footer:
		footersize = (fontsize_small * len(footer) * 0.7, fontsize_small * 2)
		footer_shape = SVG(insert=(width - footersize[0], height - footersize[1]), size=footersize)
		footer_shape.add(Rect(insert=(0, 0), size=("100%", "100%"), fill="#000"))
		footer_shape.add(
			Text(insert=("50%", "50%"), text=footer, dominant_baseline="middle", text_anchor="middle", fill="#FFF",
				 style="font-size:%ipx" % fontsize_small))
		canvas.add(footer_shape)

	return canvas
Esempio n. 7
0
 def test_simple_defs(self):
     dwg = Drawing()
     g = dwg.defs.add(Group(id='test'))
     inner_g = g.add(Group(id='innerTest'))
     result = dwg.tostring()
     self.assertEqual(result, '<svg baseProfile="full" height="100%" version="1.1" '
                              'width="100%" xmlns="http://www.w3.org/2000/svg" '
                              'xmlns:ev="http://www.w3.org/2001/xml-events" '
                              'xmlns:xlink="http://www.w3.org/1999/xlink">'
                              '<defs><g id="test"><g id="innerTest" /></g></defs></svg>')
Esempio n. 8
0
 def test_embed_stylesheet(self):
     dwg = Drawing()
     dwg.embed_stylesheet(content='.red {fill: red};')
     # stylesheet stored as <style> tag in first <defs> entity
     style = dwg.defs.elements[0]
     self.assertEqual(style.elementname, 'style')
     result = style.tostring()
     self.assertEqual(
         result,
         '<style type="text/css"><![CDATA[.red {fill: red};]]></style>')
Esempio n. 9
0
 def test_stylesheet(self):
     dwg = Drawing()
     dwg.add_stylesheet('test.css', 'Test')
     f = StringIO()
     dwg.write(f)
     result = f.getvalue()
     f.close()
     self.assertEqual(result, '<?xml version="1.0" encoding="utf-8" ?>\n'
                              '<?xml-stylesheet href="test.css" type="text/css" title="Test" alternate="no" media="screen"?>\n'
                              '<svg baseProfile="full" height="100%" version="1.1" width="100%" '
                              'xmlns="http://www.w3.org/2000/svg" xmlns:ev="http://www.w3.org/2001/xml-events" '
                              'xmlns:xlink="http://www.w3.org/1999/xlink"><defs /></svg>')
Esempio n. 10
0
 def test_non_us_ascii_chars(self):
     dwg = Drawing()
     dwg.set_desc('öäü')
     f = StringIO()
     dwg.write(f)
     result = f.getvalue()
     f.close()
     self.assertEqual(
         result, '<?xml version="1.0" encoding="utf-8" ?>\n'
         '<svg baseProfile="full" height="100%" version="1.1" width="100%" '
         'xmlns="http://www.w3.org/2000/svg" xmlns:ev="http://www.w3.org/2001/xml-events" '
         'xmlns:xlink="http://www.w3.org/1999/xlink">'
         '<title>öäü</title><defs /></svg>')
Esempio n. 11
0
    def set_properties(self, filename, title, start, end, width, height):
        """Set the properties of the canvas on which you'll want to generate your image """
        self.elements = []
        self.title = title
        self.start = start
        self.end = end
        self.width = width  # default = 200.0

        self.height = height  # default = 60.0

        self.dimension_y = self.height - self.MARGIN - self.BOTTOM_MARGIN  # this is the size of the y field
        self.dimension_x = self.width - self.MARGIN - self.RIGHT_MARGIN
        self.scale_x = float(self.dimension_x) / (
            self.end - self.start)  # this is a scaling variable
        self.y_bottom = str(round(self.dimension_y + self.MARGIN, 2))

        canvas_size = (str(self.width) + "px", "100%")
        # create drawing # Default is 100%,100% - don't override that,
        # as this allows the svg to fit the data and expand as necessary
        self.plot = Drawing(filename, size=canvas_size)
        background = Rect(insert=(0, 0), size=canvas_size, fill="white")
        self.plot.add(background)
def create_image(filename):
    image = Drawing(filename)
    image.update({"stroke": "black", "stroke_width": 1})
    return image
Esempio n. 13
0
    def make_svg(self, data):
        layers = data["layers"]
        _PROPORTION = 10
        _SHIFT_PROP = _PROPORTION / 1.5
        for f in self.forms:
            structures = [None] * len(f.id.split("_"))
            linkers    = []
            centers    = {}
            order      = {}
            maxW, maxH = 0, 0
            for cx, x in enumerate(f.id.split("_")):
                order[x] = cx
            for cl, l in enumerate(layers):
                for cs, s in enumerate(l):
                    name = f.id + "__" + s["id"]
                    if s["type"] == "H":
                        color  = "cornflowerblue" if "ref" not in s else "gainsboro"
                        shape = Circle( center = (s["shift_x"] * _SHIFT_PROP, s["shift_z"] * _SHIFT_PROP),
                                        r = 2.3 * _PROPORTION, id = name,
                                        fill = color, stroke="black",
                                        stroke_width = "2")
                    elif s["type"] == "E":
                        color  = "indianred" if "ref" not in s else "salmon"
                        rotate = f.get_ss_by_id(s["id"]).struc.goes_down()
                        shape = Triangle(center = (s["shift_x"] * _SHIFT_PROP, s["shift_z"] * _SHIFT_PROP),
                                         rc = 2.3 * _PROPORTION, id = name, fill=color,
                                         stroke = "black", stroke_width = "2",
                                         rotate = rotate)
                    else:
                        color  = "darkgreen" if "ref" not in s else "lightgreen"
                        shape = Cross(center = (s["shift_x"] * _SHIFT_PROP, s["shift_z"] * _SHIFT_PROP), r = 2.3 * _PROPORTION,
                                      fill=color, stroke="black", stroke_width = "2",
                                      id = name)
                    structures[order[s["id"]]] = shape
                    centers[s["id"]] = [s["shift_x"] * _SHIFT_PROP, s["shift_z"] * _SHIFT_PROP]
                    if s["shift_x"] * _SHIFT_PROP > maxW: maxW = s["shift_x"] * _SHIFT_PROP
                    if s["shift_z"] * _SHIFT_PROP > maxH: maxH = s["shift_z"] * _SHIFT_PROP

            for cx, x in enumerate(f.id.split("_")):
                if cx == 0 or cx == len(f.id.split("_")) - 1:
                    init = [0, 0]
                    if (ord(x[0]) - 64) <= len(layers) / 2:
                        init[1] = centers[x][1] - (2.3 * _PROPORTION * 2)
                    else:
                        init[1] = centers[x][1] + (2.3 * _PROPORTION * 2)
                    if int(re.search("(\d+)", x).group(1)) <= len(layers[ord(x[0]) - 65]) / 2:
                        init[0] = centers[x][0] - (2.3 * _PROPORTION * 2)
                    else:
                        init[0] = centers[x][0] + (2.3 * _PROPORTION * 2)
                    if cx == 0:
                        shape = Line(init, centers[x], stroke="darkblue", stroke_width = "4")
                    elif cx == len(f.id.split("_")) - 1:
                        shape = Line(centers[x], init, stroke="darkred", stroke_width = "4")
                    linkers.append(shape)
                for cy, y in enumerate(f.id.split("_")):
                    if cy == cx + 1:
                        shape = Line(centers[x], centers[y], stroke="black", stroke_width = "4")
                        linkers.append(shape)

            # Intercalate
            toplink = []
            dowlink = []
            if f.sslist[0].struc.goes_up():
                dowlink = linkers[0:][::2]
                toplink = linkers[1:][::2]
            else:
                dowlink = linkers[1:][::2]
                toplink = linkers[0:][::2]

            g = Group()
            for x in dowlink:
                g.add(x)
            for x in structures:
                g.add(x)
            for x in toplink:
                g.add(x)
            g.translate(2.3 * _PROPORTION * 3, 2.3 * _PROPORTION * 3)
            d = Drawing(size = (maxW + ((2.3 * _PROPORTION * 3) * 2),
                                maxH + ((2.3 * _PROPORTION * 3) * 2)),
                        id = f.id + "__image")
            d.add(g)
            for x in data["forms"]:
                if x["id"] == f.id:
                    x["svg"] = d.tostring()
Esempio n. 14
0
    def __init__(self,
                 width=600,
                 height=400,
                 margin_top=20,
                 margin_bottom=40,
                 margin_left=40,
                 margin_right=20,
                 x_min=0,
                 y_min=None,
                 x_max=1,
                 y_max=None,
                 debug=False,
                 graph_colour="midnightblue",
                 background=None,
                 x_label=None,
                 y_label=None,
                 y_label_max_min=True,
                 title=None):

        self.width = width
        self.height = height
        self.debug = debug
        self.margin_top = margin_top
        self.margin_bottom = margin_bottom
        self.margin_left = margin_left
        self.margin_right = margin_right
        self.x_max = x_max
        self.y_max = y_max
        self.x_min = x_min
        self.y_min = y_min
        self.graph_colour = graph_colour
        self.x_label = x_label
        self.y_label = y_label
        self.y_label_max_min = y_label_max_min
        self.title = title
        self.font_size = 15

        self.plottable_x = self.width - (self.margin_left + self.margin_right)
        self.plottable_y = self.height - (self.margin_top + self.margin_bottom)

        # start drawing object
        self.plot = Drawing(
            debug=self.debug,
            size=(self.width, self.height),
            # viewBox = ("0 0 " + str(float(length) + 10) + " " + str(float(width) + 10)),
            preserveAspectRatio="xMinYMin meet"
        )  # , size=('200mm', '150mm'), viewBox=('0 0 200 150'))

        if background:
            self.plot.add(
                Rect(insert=(0, 0),
                     size=(self.width, self.height),
                     fill=background))

        if x_label:
            self.plottable_y -= self.font_size
            self.add_x_label()

        if y_label:
            self.plottable_x -= self.font_size
            self.margin_left += self.font_size
            self.add_y_label()

        if title:
            self.plottable_y -= self.font_size + 5
            self.margin_top += self.font_size + 5
            self.add_title()

        self.plot.add(
            Line(start=(self.margin_left - 4, self.margin_top),
                 end=(self.margin_left - 4,
                      self.margin_top + self.plottable_y),
                 stroke_width=1,
                 stroke=self.graph_colour))
        self.plot.add(
            Line(start=(self.margin_left,
                        self.margin_top + self.plottable_y + 4),
                 end=(self.margin_left + self.plottable_x,
                      self.margin_top + self.plottable_y + 4),
                 stroke_width=1,
                 stroke=self.graph_colour))

        if self.y_label_max_min and self.y_max and self.y_min:
            self.add_y_max_min(self.y_max, self.y_min)
def _blank_drawing(width: int, height: int) -> Drawing:
    base = Drawing(viewBox=f'0 0 {int(width)} {int(height)}', size=(None, None), debug=False, profile='tiny')
    return base