示例#1
0
def save_figure(figure, file_format, width, height, units, dpi, filename):
    pio.orca.config.use_xvfb = True
    # set width and height from 96 dpi standard density
    # this is just for the svg
    width, height = DashboardModel.reference_image_size(
        width, height, units, dpi)
    figure['layout']['width'] = width
    figure['layout']['height'] = height

    # create parent directory if it does not exist
    pathlib.Path(filename).parent.mkdir(parents=True, exist_ok=True)
    if file_format in ('svg', 'pdf'):
        # these are vector formats directly supported by orca
        # because they're vector formats we don't worry about scale
        pio.write_image(figure,
                        filename.as_posix(),
                        height=int(height),
                        width=int(width))
    elif file_format == 'eps':
        tmp_name = tempfile.mktemp('.svg')
        pio.write_image(figure, tmp_name, height=int(height), width=int(width))
        cairosvg.svg2ps(url=tmp_name, write_to=filename.as_posix())
        os.remove(tmp_name)
    else:
        # TIFF or JPG or PNG, need to use ImageMagick to set DPI
        tmp_name = tempfile.mktemp('.png')
        pio.write_image(figure,
                        tmp_name,
                        height=int(height),
                        width=int(width),
                        scale=dpi / 96)
        with Image(filename=tmp_name, resolution=dpi) as img:
            img.save(filename=filename.as_posix())
        os.remove(tmp_name)
    return filename
    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))
示例#3
0
def create_image(svg):
    filename = "new.ps"
    with open(filename, "w") as f:
        cairosvg.svg2ps(bytestring=svg, write_to=f)

    image = Image.open(filename)
    image_full_size = max(image.size) * 3/2
    white_image = Image.new("RGB", (image_full_size, image_full_size), "white")
    top_left = ((image_full_size - image.size[0]) / 2, (image_full_size - image.size[1]) / 2)
    white_image.paste(image, box=top_left)
    return white_image
示例#4
0
文件: tools.py 项目: jwcarr/shepard
def convert_svg(svg_file_path, out_file_path, png_width=1000):
    import cairosvg
    filename, extension = path.splitext(out_file_path)
    if extension not in ['.pdf', '.eps', '.png']:
        raise ValueError('Invalid format. Use either .pdf, .eps, or .png')
    if extension == '.pdf':
        cairosvg.svg2pdf(url=svg_file_path, write_to=out_file_path)
    elif extension == '.eps':
        cairosvg.svg2ps(url=svg_file_path, write_to=out_file_path)
    elif extension == '.png':
        cairosvg.svg2png(url=svg_file_path, write_to=out_file_path, dpi=300)
示例#5
0
def svg2Image(svg_file, dst, fmt='pdf', dpi=96):
    if 0:  # svglib
        drawing = svg2rlg(svg_file)
        if fmt == 'pdf':
            renderPDF.drawToFile(drawing, dst)
        elif fmt == 'png':
            renderPM.drawToFile(drawing, dst, fmt="PNG", dpi=300)

    else:  # cairosvg default dpi=96
        if fmt == 'pdf':
            cairosvg.svg2pdf(url=svg_file, write_to=dst, dpi=dpi)
        elif fmt == 'png':
            cairosvg.svg2png(url=svg_file, write_to=dst, dpi=dpi)
        elif fmt == 'ps':
            cairosvg.svg2ps(url=svg_file, write_to=dst, dpi=dpi)
        else:
            print('error, format=', fmt)
示例#6
0
 def save_figure(self,
                 figure,
                 file_format,
                 width,
                 height,
                 units,
                 dpi,
                 filename=None):
     pio.orca.config.use_xvfb = True
     if filename is None:
         filename = f'{",".join([str(col_id) for col_id in self._loaded_collection_ids])}.{file_format}'
         filename = os.path.join(self.root_dir, filename)
     # set width and height from 96 dpi standard density
     # this is just for the svg
     width, height = self.reference_image_size(width, height, units, dpi)
     figure['layout']['width'] = width
     figure['layout']['height'] = height
     if file_format in ('svg', 'pdf'):
         # these are vector formats directly supported by orca
         # because they're vector formats we don't worry about scale
         pio.write_image(figure,
                         filename,
                         height=int(height),
                         width=int(width))
     elif file_format == 'eps':
         tmp_name = os.path.join(self.root_dir, 'tmp.svg')
         pio.write_image(figure,
                         tmp_name,
                         height=int(height),
                         width=int(width))
         cairosvg.svg2ps(url=tmp_name, write_to=filename)
         os.remove(tmp_name)
     else:
         # TIFF or JPG or PNG, need to use ImageMagick to set DPI
         tmp_name = os.path.join(
             self.root_dir, 'tmp.png')  # PNG is lossless so we should be ok
         pio.write_image(figure,
                         tmp_name,
                         height=int(height),
                         width=int(width),
                         scale=dpi / 96)
         with Image(filename=tmp_name, resolution=dpi) as img:
             img.save(filename=filename)
         os.remove(tmp_name)
     return filename
示例#7
0
def route_save_image():
    image_format = flask.request.form['format']
    svg = flask.request.form['svg']
    if image_format == 'pdf':
        data = cairosvg.svg2pdf(bytestring=svg)
        mimetype = 'application/pdf'
    elif image_format == 'png':
        data = cairosvg.svg2png(bytestring=svg)
        mimetype = 'image/png'
    elif image_format == 'ps':
        data = cairosvg.svg2ps(bytestring=svg)
        mimetype = 'application/postscript'
    elif image_format == 'svg':
        data = cairosvg.svg2svg(bytestring=svg)
        mimetype = 'image/svg+xml'
    elif image_format == 'raw-svg':
        data = svg
        mimetype = 'image/svg+xml'
    else:
        flask.abort(400)
    return flask.Response(data, mimetype=mimetype)
示例#8
0
def qasm2ps(qasm_str: str,
            basis: str = ('id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,'
                          'cx,cy,cz,ch,crz,cu1,cu3,swap,ccx'),
            show_clbits: bool = True,
            scale: float = 1.0) -> bytes:
    """Transform a QASM code to a PS file.

    This method output the PostScript representation of the quantum circuit
    provided as a QASM program.

    Remark: not all gates are implemented. If a gate is not implemented
            then a message will be printed to warn the user and the gate
            will not be drawn in the PS.
            If you want to implement more gates see the _draw_gate method
            in ./svg/drawing.py.

    Args:
        qasm_str    (str)  : The QASM quantum circuit to draw in PS.
        basis       (list) : The gate basis used to represent the circuit.
        show_clbits (bool) : Flag that control the drawing of classical bit
                             lines.
        scale       (float): The scaling imposed to the produced PostScript
        file.

    Returns:
        bytes: The PostScript representation of the given QASM circuit.
    """

    # Generate the SVG first.
    svg, (_, _) = qasm2svg.qasm2svg(qasm_str,
                                    basis=basis,
                                    show_clbits=show_clbits,
                                    output_dimensions=True)
    # And generate PS
    ps_bytes = svg2ps(bytestring=svg.encode('utf-8'), scale=scale)

    return ps_bytes
示例#9
0
    def save(self, uri_dest, **kargs):
        tree = etree.parse(self.template_path)
        d = self.data

        with open(d['recipient_image'], 'rb') as recipient_image:
            image_data = recipient_image.read()
            image_mime_type = magic.from_buffer(image_data, mime=True)
            image_base_64 = base64.b64encode(image_data)

        el_image = tree.xpath(self.el_selectors['recipient_image'],
                              namespaces=NSMAP)[0]
        el_image.attrib[
            '{http://www.w3.org/1999/xlink}href'] = 'data:{};base64,{}'.format(
                image_mime_type, image_base_64.decode('utf-8'))

        recipient_name_parts = d['recipient_name'].split()

        if len(recipient_name_parts) > 3:
            recipient_name_part_1 = ' '.join(recipient_name_parts[:3])
            recipient_name_part_2 = ' '.join(recipient_name_parts[3:])
        else:
            recipient_name_part_1, recipient_name_part_2 = ' '.join(
                recipient_name_parts), ''

        el_r_name_part_1 = tree.xpath(
            self.el_selectors['recipient_name_part_1'], namespaces=NSMAP)[0]
        el_r_name_part_1.text = recipient_name_part_1.upper()

        el_r_name_part_2 = tree.xpath(
            self.el_selectors['recipient_name_part_2'], namespaces=NSMAP)[0]
        el_r_name_part_2.text = recipient_name_part_2.upper()

        el_r_blood_type = tree.xpath(self.el_selectors['recipient_bloodtype'],
                                     namespaces=NSMAP)[0]
        el_r_blood_type.text = self.data['recipient_bloodtype'].upper()

        el_l_name = tree.xpath(self.el_selectors['location_name'],
                               namespaces=NSMAP)[0]
        el_l_name.text = self.data['location_name'].upper()

        el_l_address_part_1 = tree.xpath(
            self.el_selectors['location_address_part_1'], namespaces=NSMAP)[0]
        el_l_address_part_1.text = '{}, {}'.format(
            self.data['location_address_street'].upper(),
            self.data['location_address_number'].upper())
        el_l_address_part_2 = tree.xpath(
            self.el_selectors['location_address_part_2'], namespaces=NSMAP)[0]
        el_l_address_part_2.text = '{}, {} - {}, {}'.format(
            self.data['location_address_district'].upper(),
            self.data['location_address_locality'].upper(),
            self.data['location_address_region'].upper(),
            self.data['location_address_postal_code'].upper(),
        )

        uri = urlparse(uri_dest)
        file_format = uri.path.rpartition('.')[-1].lower()
        file_args = {'uid': self.uid, 'format': file_format}

        if uri.scheme == 'gs':
            fp = '/tmp/hematopy-img-{uid}.{format}'.format(**file_args)
        else:
            fp = uri.path.format(**file_args)

        if file_format == 'png':
            cairosvg.svg2png(bytestring=etree.tostring(tree), write_to=fp)
        if file_format == 'pdf':
            cairosvg.svg2pdf(bytestring=etree.tostring(tree), write_to=fp)
        if file_format == 'ps':
            cairosvg.svg2ps(bytestring=etree.tostring(tree), write_to=fp)
        if file_format == 'svg':
            cairosvg.svg2svg(bytestring=etree.tostring(tree), write_to=fp)

        if uri.scheme == 'gs':
            client = storage.storage_gc.Client()
            file_path = uri.path.format(**file_args)

            with open(fp, 'rb') as file:
                object_stream = storage.GCSObjectStreamUpload(
                    client,
                    bucket_name=uri.netloc,
                    blob_name=file_path,
                )

                def file_read_chunked(file, chunk_size):
                    return iter(lambda: file.read(chunk_size), '')

                with open(fp, 'rb') as file:
                    with object_stream as obj_stream:
                        file_chunks = file_read_chunked(
                            file, obj_stream._chunk_size)
                        for data in file_chunks:
                            obj_stream.write(data)
                            if data == b'':
                                break

            os.remove(fp)

        _d = d.copy()
        (_d.pop(k) for k in 'recipient_name recipient_image'.split())
        logger.info({
            'type': 'banner_generated',
            'data': {
                'donation': _d,
                '_meta': {
                    'file_format': file_format,
                }
            },
        })
        return True,

        error_message = '''
"{}" is invalid file extension! The supported extension is "png". "pdf", "ps" and "svg".
'''
        raise ValueError(error_message.format(fp))
示例#10
0
    def save(self, fp, **params):
        tree = etree.parse(self.template_path)
        d = self.data

        with open(d['recipient_image'], 'rb') as recipient_image:
            image_data = recipient_image.read()
            image_mime_type = magic.from_buffer(image_data, mime=True)
            image_base_64 = base64.b64encode(image_data)

        el_image = tree.xpath(self.el_selectors['recipient_image'],
                              namespaces=NSMAP)[0]
        el_image.attrib[
            '{http://www.w3.org/1999/xlink}href'] = 'data:{};base64,{}'.format(
                image_mime_type, image_base_64.decode('utf-8'))

        recipient_name_parts = d['recipient_name'].split()

        if len(recipient_name_parts) > 3:
            recipient_name_part_1 = ' '.join(recipient_name_parts[:3])
            recipient_name_part_2 = ' '.join(recipient_name_parts[3:])
        else:
            recipient_name_part_1, recipient_name_part_2 = name, ''

        el_r_name_part_1 = tree.xpath(
            self.el_selectors['recipient_name_part_1'], namespaces=NSMAP)[0]
        el_r_name_part_1.text = recipient_name_part_1.upper()

        el_r_name_part_2 = tree.xpath(
            self.el_selectors['recipient_name_part_2'], namespaces=NSMAP)[0]
        el_r_name_part_2.text = recipient_name_part_2.upper()

        el_r_blood_type = tree.xpath(self.el_selectors['recipient_image'],
                                     namespaces=NSMAP)[0]
        el_r_blood_type.text = self.data['recipient_blood_type'].upper()

        el_l_name = tree.xpath(self.el_selectors['location_name'],
                               namespaces=NSMAP)[0]
        el_l_name.text = self.data['location_name'].upper()

        el_l_address_part_1 = tree.xpath(
            self.el_selectors['location_address_part_1'], namespaces=NSMAP)[0]
        el_l_address_part_1.text = '{}, {}'.format(
            self.data['location_address_street'].upper(),
            self.data['location_address_number'].upper())
        el_l_address_part_2 = tree.xpath(
            self.el_selectors['location_address_part_2'], namespaces=NSMAP)[0]
        el_l_address_part_2.text = '{}, {} - {}, {}'.format(
            self.data['location_address_district'].upper(),
            self.data['location_address_locality'].upper(),
            self.data['location_address_region'].upper(),
            self.data['location_address_postal_code'].upper(),
        )

        file_format = fp.rpartition('.')[-1].lower()

        if file_format == 'png':
            cairosvg.svg2png(bytestring=etree.tostring(tree), write_to=fp)
        if file_format == 'pdf':
            cairosvg.svg2pdf(bytestring=etree.tostring(tree), write_to=fp)
        if file_format == 'ps':
            cairosvg.svg2ps(bytestring=etree.tostring(tree), write_to=fp)
        if file_format == 'svg':
            cairosvg.svg2svg(bytestring=etree.tostring(tree), write_to=fp)

        _d = d.copy()
        (_d.pop(k) for k in 'recipient_name recipient_image'.split())
        logger.info({
            'type': 'banner_generated',
            'data': {
                'donation': _d,
                '_meta': {
                    'file_format': file_format,
                }
            },
        })
        return True

        error_message = '''
"{}" is invalid file extension! The supported extension is "png". "pdf", "ps" and "svg".
'''
        raise ValueError(error_message.format(fp))
示例#11
0
文件: image.py 项目: agrumery/aGrUM
def exportInference(model, filename=None, **kwargs):
    """
  the graphical representation of an inference in a notebook

  Parameters
  ----------
  model: pyAgrum:GraphicalModel
      the model in which to infer (pyAgrum.BayesNet, pyAgrum.MarkovNet or pyAgrum.InfluenceDiagram)
  filename: str
      the name of the resulting file (suffix in ['pdf', 'png', 'ps']). If filename is None, the result is a np.array ready to be used with imshow().
  engine: pyAgrum.Inference
      inference algorithm used. If None, gum.LazyPropagation will be used for BayesNet,gum.ShaferShenoy for gum.MarkovNet and gum.ShaferShenoyLIMIDInference for gum.InfluenceDiagram.
  evs: Dict[str,str|int]
      map of evidence
  targets: Set[str|int]
      set of targets
  size: str
      size of the rendered graph
  nodeColor: Dict[int,float]
      a nodeMap of values (between 0 and 1) to be shown as color of nodes (with special colors for 0 and 1)
  factorColor: Dict[int,float]
      a nodeMap of values (between 0 and 1) to be shown as color of factors (in MarkovNet representation)
  arcWidth: Dict[(int,int),float]
      a arcMap of values to be shown as width of arcs
  arcColor: Dict[(int,int),float]
      a arcMap of values (between 0 and 1) to be shown as color of arcs
  cmap: matplotlib.colors.ColorMap
      color map to show the color of nodes and arcs
  cmapArc: matplotlib.colors.ColorMap
      color map to show the vals of Arcs.
  graph: pyAgrum.Graph
      only shows nodes that have their id in the graph (and not in the whole BN)
  view: str
      graph | factorgraph | None (default) for Markov network

  Returns
  -------
  str|dot.Dot
    the desired representation of the inference
  """
    if filename is None:
        tmp = tempfile.NamedTemporaryFile(suffix='.png', delete=False)
        exportInference(model, tmp.name, **kwargs)
        img = mpimg.imread(tmp.name)
        try:
            os.remove(tmp.name)
        except PermissionError:  # probably windows error : file still 'used' ... grrr...
            pass
        return img

    fmt_image = filename.split(".")[-1]
    if fmt_image not in ['pdf', 'png', 'ps']:
        raise Exception(
            f"{filename} in not a correct filename for export : extension '{fmt_image}' not in [pdf,png,ps]."
        )

    import cairosvg

    if "size" in kwargs:
        size = kwargs['size']
    else:
        size = gum.config["notebook", "default_graph_inference_size"]

    svgtxt = dot_as_svg_string(prepareShowInference(model, **kwargs),
                               size=size)

    if fmt_image == "pdf":
        cairosvg.svg2pdf(bytestring=svgtxt, write_to=filename)
    elif fmt_image == "png":
        cairosvg.svg2png(bytestring=svgtxt, write_to=filename)
    else:  # format=="ps"
        cairosvg.svg2ps(bytestring=svgtxt, write_to=filename)