def draw_aafigure(block_text: str,
                  filename: typ.Any = None,
                  output_fmt: str = 'svg') -> bytes:
    # pylint:disable=unused-argument
    warnings.warn("draw_aafigure is depricated use 'draw_aafig' instead",
                  DeprecationWarning)
    if output_fmt == 'png':
        tag_type = 'img_base64_png'
    elif output_fmt == 'svg':
        tag_type = 'img_base64_svg'
    elif output_fmt == 'svg':
        tag_type = 'img_utf8_svg'
    else:
        tag_type = 'img_base64_svg'

    default_options: Options = {'tag_type': tag_type}
    block_text, tag_type, options = _parse_block_text(block_text,
                                                      default_options)

    _, output = aafigure.render(block_text, options=options)
    result = output.getvalue()
    if isinstance(result, str):
        return result.encode("utf-8")
    if isinstance(result, bytes):
        return result

    errmsg = f"Unexpected return type from aafigure.render: {type(result)}"
    raise TypeError(errmsg)
def draw_aafig(block_text: str, default_options: Options = None) -> str:
    block_text, tag_type, options = _parse_block_text(block_text,
                                                      default_options)

    _, output = aafigure.render(block_text, options=options)
    img_data = output.getvalue()
    return img2html(img_data, tag_type)
Beispiel #3
0
def render_aafigure(app, text, options):
    """
    Render an ASCII art figure into the requested format output file.
    """

    if aafigure is None:
        raise AafigError("aafigure module not installed")

    fname = get_basename(text, options)
    fname = "{}.{}".format(get_basename(text, options), options["format"])
    if app.builder.format == "html":
        # HTML
        imgpath = relative_uri(app.builder.env.docname, "_images")
        relfn = posixpath.join(imgpath, fname)
        outfn = path.join(app.builder.outdir, "_images", fname)
    else:
        # Non-HTML
        if app.builder.format != "latex":
            logger.warn("aafig: the builder format %s is not officially "
                        "supported, aafigure images could not work. "
                        "Please report problems and working builder to "
                        "avoid this warning inthe future" % app.builder.format)
        relfn = fname
        outfn = path.join(app.builder.outdir, fname)
    metadata_fname = "%s.aafig" % outfn

    try:
        if path.isfile(outfn):
            extra = None
            if options["format"].lower() == "svg":
                f = None
                try:
                    try:
                        f = open(metadata_fname)
                        extra = f.read()
                    except Exception:
                        raise AafigError()
                finally:
                    if f is not None:
                        f.close()
            return relfn, outfn, id, extra
    except AafigError:
        pass

    ensuredir(path.dirname(outfn))

    try:
        (visitor, output) = aafigure.render(text, outfn, options)
        output.close()
    except aafigure.UnsupportedFormatError as e:
        raise AafigError(str(e))

    extra = None
    if options["format"].lower() == "svg":
        extra = visitor.get_size_attrs()
        f = open(metadata_fname, "w")
        f.write(extra)
        f.close()

    return relfn, outfn, id, extra
def AAFigureDirective(name, arguments, options, content, lineno,
                      content_offset, block_text, state, state_machine):
    text = '\n'.join(content)

    global aafigure_counter

    # ensure that options are present and initialized with defaults if not given
    if not options.has_key('background'): options['background'] = '#ffffff'
    if not options.has_key('foreground'): options['foreground'] = '#000000'
    if not options.has_key('fill'):
        options['fill'] = options['foreground']  # fill = fore by default
    if not options.has_key('scale'): options['scale'] = 1
    if not options.has_key('line_width'): options['line_width'] = 2
    if not options.has_key('format'): options['format'] = DEFAULT_FORMAT
    if not options.has_key('aspect'): options['aspect'] = 1
    if not options.has_key('proportional'): options['proportional'] = False
    if not options.has_key('name'):
        options['name'] = 'aafigure-%i' % aafigure_counter
        aafigure_counter += 1

    output_name = options['name'] + '.' + options['format'].lower()
    try:
        (visitor, output) = aafigure.render(text, output_name, options)
    except aafigure.UnsupportedFormatError, e:
        result = [
            state_machine.reporter.error(str(e),
                                         nodes.literal_block(
                                             block_text, block_text),
                                         line=lineno)
        ]
def AAFigureDirective(name, arguments, options, content, lineno,
                  content_offset, block_text, state, state_machine):
    text = '\n'.join(content)

    global aafigure_counter

    # ensure that options are present and initialized with defaults if not given
    if not options.has_key('background'): options['background'] = '#ffffff'
    if not options.has_key('foreground'): options['foreground'] = '#000000'
    if not options.has_key('fill'): options['fill'] = options['foreground'] # fill = fore by default
    if not options.has_key('scale'): options['scale'] = 1
    if not options.has_key('line_width'): options['line_width'] = 2
    if not options.has_key('format'): options['format'] = DEFAULT_FORMAT
    if not options.has_key('aspect'): options['aspect'] = 1
    if not options.has_key('proportional'): options['proportional'] = False
    if not options.has_key('name'):
        options['name'] = 'aafigure-%i' % aafigure_counter
        aafigure_counter += 1

    output_name = options['name'] + '.' + options['format'].lower()
    try:
        (visitor, output) = aafigure.render(text, output_name, options)
    except aafigure.UnsupportedFormatError, e:
        result = [state_machine.reporter.error(str(e),
            nodes.literal_block(block_text, block_text),
            line=lineno
        )]
Beispiel #6
0
def render_aafigure(app, text, options):
    """
    Render an ASCII art figure into the requested format output file.
    """
    _id = None
    if aafigure is None:
        raise AafigError('aafigure module not installed')

    fname = '%s.%s' % (get_basename(text, options), options['format'])
    if app.builder.format == 'html':
        # HTML
        imgpath = relative_uri(app.builder.env.docname, '_images')
        relfn = posixpath.join(imgpath, fname)
        outfn = path.join(app.builder.outdir, '_images', fname)
    else:
        # Non-HTML
        if app.builder.format != 'latex':
            app.builder.warn(
                'aafig: the builder format %s is not officially '
                'supported, aafigure images could not work. Please report '
                'problems and working builder to avoid this warning in '
                'the future' % app.builder.format)
        relfn = fname
        outfn = path.join(app.builder.outdir, fname)
    metadata_fname = '%s.aafig' % outfn

    try:
        if path.isfile(outfn):
            extra = None
            if options['format'].lower() == 'svg':
                f = None
                try:
                    try:
                        with open(metadata_fname, 'r') as f:
                            extra = f.read()
                    except Exception:
                        raise AafigError()
                finally:
                    if f is not None:
                        f.close()
            return relfn, outfn, _id, extra
    except AafigError:
        pass

    ensuredir(path.dirname(outfn))

    try:
        (visitor, output) = aafigure.render(text, outfn, options)
        output.close()
    except aafigure.UnsupportedFormatError as e:
        raise AafigError(str(e))

    extra = None
    if options['format'].lower() == 'svg':
        extra = visitor.get_size_attrs()
        with open(metadata_fname, 'w') as f:
            f.write(extra)

    return relfn, outfn, _id, extra
Beispiel #7
0
def render_aafigure(app, text, options):
    """
    Render an ASCII art figure into the requested format output file.
    """
    _id = None
    if aafigure is None:
        raise AafigError('aafigure module not installed')

    fname = '%s.%s' % (get_basename(text, options), options['format'])
    if app.builder.format == 'html':
        # HTML
        imgpath = relative_uri(app.builder.env.docname, '_images')
        relfn = posixpath.join(imgpath, fname)
        outfn = path.join(app.builder.outdir, '_images', fname)
    else:
        # Non-HTML
        if app.builder.format != 'latex':
            app.builder.warn('aafig: the builder format %s is not officially '
                    'supported, aafigure images could not work. Please report '
                    'problems and working builder to avoid this warning in '
                    'the future' % app.builder.format)
        relfn = fname
        outfn = path.join(app.builder.outdir, fname)
    metadata_fname = '%s.aafig' % outfn

    try:
        if path.isfile(outfn):
            extra = None
            if options['format'].lower() == 'svg':
                f = None
                try:
                    try:
                        with open(metadata_fname, 'r') as f:
                            extra = f.read()
                    except Exception:
                        raise AafigError()
                finally:
                    if f is not None:
                        f.close()
            return relfn, outfn, _id, extra
    except AafigError:
        pass

    ensuredir(path.dirname(outfn))

    try:
        (visitor, output) = aafigure.render(text, outfn, options)
        output.close()
    except aafigure.UnsupportedFormatError as e:
        raise AafigError(str(e))

    extra = None
    if options['format'].lower() == 'svg':
        extra = visitor.get_size_attrs()
        with open(metadata_fname, 'w') as f:
            f.write(extra)

    return relfn, outfn, _id, extra
Beispiel #8
0
    def render(self, formatter):
        """text to image conversion"""
        key = 'aafigure_%s' % (cache.key(self.request,
                                         itemname=self.pagename,
                                         content="%s%s" %
                                         (self.raw, self.args)), )
        if not cache.exists(self.request, key) or not cache.exists(
                self.request, key + '_size'):
            # not in cache, regenerate image
            options = dict(format='svg')
            for arg in self.args.split():
                try:
                    k, v = arg.split('=', 1)
                except ValueError:  # when splitting fails
                    k = arg
                    v = None
                if k == 'aspect':
                    options['aspect'] = float(v)
                elif k == 'scale':
                    options['scale'] = float(v)
                elif k == 'textual':
                    options['textual'] = True
                elif k == 'proportional':
                    options['proportional'] = True
                elif k == 'linewidth':
                    options['linewidth'] = float(v)
                elif k == 'foreground':
                    options['foreground'] = sanitizte_color(v)
                elif k == 'fill':
                    options['fill'] = sanitizte_color(v)
                # no 'background' as SVG backend ignores that
                # no generic options
                # XXX unknown options are ignored with no message

            visitor, output = aafigure.render(self.raw, None, options)
            cache.put(self.request,
                      key,
                      output.getvalue(),
                      content_type="image/svg+xml")
            # need to store the size attributes too
            cache.put(self.request,
                      key + '_size',
                      visitor.get_size_attrs(),
                      content_type="text/plain")

        # get the information from the cache
        #~ return formatter.image(src=cache.url(self.request, key), alt=xxx)
        # XXX this currently only works for HTML, obviously...
        return formatter.rawHTML(
            '<object type="image/svg+xml" data="%s" %s></object>' % (
                cache.url(self.request, key),
                cache._get_datafile(
                    self.request,
                    key + '_size').read()  # XXX no way to directly read cache?
            ))
def render_aafigure(app, text, options):
    """
    Render an ASCII art figure into the requested format output file.
    """

    if aafigure is None:
        raise AafigError("aafigure module not installed")

    fname = get_basename(text, options)
    fname = "%s.%s" % (get_basename(text, options), options["format"])
    if app.builder.format == "html":
        # HTML
        imgpath = relative_uri(app.builder.env.docname, "_images")
        relfn = posixpath.join(imgpath, fname)
        outfn = path.join(app.builder.outdir, "_images", fname)
    else:
        # Non-HTML
        if app.builder.format != "latex":
            app.builder.warn(
                "aafig: the builder format %s is not officially "
                "supported, aafigure images could not work. Please report "
                "problems and working builder to avoid this warning in "
                "the future" % app.builder.format
            )
        relfn = fname
        outfn = path.join(app.builder.outdir, fname)
    metadata_fname = "%s.aafig" % outfn

    try:
        if path.isfile(outfn):
            extra = None
            if options["format"].lower() == "svg":
                f = None
                try:
                    try:
                        f = file(metadata_fname, "r")
                        extra = f.read()
                    except:
                        raise AafigError()
                finally:
                    if f is not None:
                        f.close()
            return relfn, outfn, id, extra
    except AafigError:
        pass

    ensuredir(path.dirname(outfn))

    try:
        (visitor, output) = aafigure.render(text, outfn, options)
        output.close()
    except aafigure.UnsupportedFormatError, e:
        raise AafigError(str(e))
def render_aafigure(self, text, options):
    """
    Render an ASCII art figure into the requested format output file.
    """

    fname = get_basename(text, options)
    fname = '%s.%s' % (get_basename(text, options), options['format'])
    if True: #TODO: hasattr(self.builder, 'imgpath'):
        # HTML
        #TODO relfn = posixpath.join(self.builder.imgpath, fname)
        relfn = '_build/html/_images/' + fname
        #TODO: outfn = path.join(self.builder.outdir, '_images', fname)
        outfn = '/home/luca/repos/aafigure/documentation/_build/html/_images/' + fname
    else:
        # LaTeX
        relfn = fname
        outfn = path.join(self.builder.outdir, fname)
    metadata_fname = '%s.aafig' % outfn

    try:
        if path.isfile(outfn):
            extra = None
            if options['format'].lower() == 'svg':
                f = None
                try:
                    try:
                        f = file(metadata_fname, 'r')
                        extra = f.read()
                    except:
                        raise AafigError()
                finally:
                    if f is not None:
                        f.close()
            return relfn, outfn, id, extra
    except AafigError:
        pass

    ensuredir(path.dirname(outfn))

    try:
        (visitor, output) = aafigure.render(text, outfn, options)
	output.close()
    except aafigure.UnsupportedFormatError, e:
        raise AafigError(str(e))
def render_aafigure(self, text, options):
    """
    Render an ASCII art figure into the requested format output file.
    """

    fname = get_basename(text, options)
    fname = '%s.%s' % (get_basename(text, options), options['format'])
    if True: #TODO: hasattr(self.builder, 'imgpath'):
        # HTML
        #TODO relfn = posixpath.join(self.builder.imgpath, fname)
        relfn = '_build/html/_images/' + fname
        #TODO: outfn = path.join(self.builder.outdir, '_images', fname)
        outfn = '/home/luca/repos/aafigure/documentation/_build/html/_images/' + fname
    else:
        # LaTeX
        relfn = fname
        outfn = path.join(self.builder.outdir, fname)
    metadata_fname = '%s.aafig' % outfn

    try:
        if path.isfile(outfn):
            extra = None
            if options['format'].lower() == 'svg':
                f = None
                try:
                    try:
                        f = file(metadata_fname, 'r')
                        extra = f.read()
                    except:
                        raise AafigError()
                finally:
                    if f is not None:
                        f.close()
            return relfn, outfn, id, extra
    except AafigError:
        pass

    ensuredir(path.dirname(outfn))

    try:
        (visitor, output) = aafigure.render(text, outfn, options)
	output.close()
    except aafigure.UnsupportedFormatError, e:
        raise AafigError(str(e))
Beispiel #12
0
    def render(self, formatter):
        """text to image conversion"""
        key = 'aafigure_%s' % (cache.key(self.request, itemname=self.pagename, content="%s%s" % (self.raw, self.args)),)
        if not cache.exists(self.request, key) or not cache.exists(self.request, key+'_size'):
            # not in cache, regenerate image
            options = dict(format='svg')
            for arg in self.args.split():
                try:
                    k, v = arg.split('=', 1)
                except ValueError:  # when splitting fails
                    k = arg
                    v = None
                if k == 'aspect':
                    options['aspect'] = float(v)
                elif k == 'scale':
                    options['scale'] = float(v)
                elif k == 'textual':
                    options['textual'] = True
                elif k == 'proportional':
                    options['proportional'] = True
                elif k == 'linewidth':
                    options['linewidth'] = float(v)
                elif k == 'foreground':
                    options['foreground'] = sanitizte_color(v)
                elif k == 'fill':
                    options['fill'] = sanitizte_color(v)
                # no 'background' as SVG backend ignores that
                # no generic options
                # XXX unknown options are ignored with no message

            visitor, output = aafigure.render(self.raw, None, options)
            cache.put(self.request, key, output.getvalue(), content_type="image/svg+xml")
            # need to store the size attributes too
            cache.put(self.request, key+'_size', visitor.get_size_attrs(), content_type="text/plain")

        # get the information from the cache
        #~ return formatter.image(src=cache.url(self.request, key), alt=xxx)
        # XXX this currently only works for HTML, obviously...
        return formatter.rawHTML('<object type="image/svg+xml" data="%s" %s></object>' % (
            cache.url(self.request, key),
            cache._get_datafile(self.request, key+'_size').read() # XXX no way to directly read cache?
        ))
Beispiel #13
0
def render_aafigure(self, text, options):
    """
    Render an ASCII art figure into the requested format output file.
    """

    fname = get_basename(text, options)

    if hasattr(self.builder, 'imgpath'):
        # HTML
        relfn = posixpath.join(self.builder.imgpath, fname)
        outfn = path.join(self.builder.outdir, '_images', fname)
    else:
        # LaTeX
        relfn = fname
        outfn = path.join(self.builder.outdir, fname)
    metadata_fname = f'{outfn}.aafig'

    try:
        if path.isfile(outfn):
            extra = None
            if options['format'].lower() == 'svg':
                f = None
                try:
                    try:
                        f = file(metadata_fname, 'r')
                        extra = f.read()
                    except:
                        raise AafigError()
                finally:
                    if f is not None:
                        f.close()
            return relfn, outfn, id, extra
    except AafigError:
        pass

    ensuredir(path.dirname(outfn))

    try:
        (visitor, output) = aafigure.render(text, outfn, options)
	output.close()
    except aafigure.UnsupportedFormatError, e:
        raise AafigError(str(e))
Beispiel #14
0
    def render(self, options, data, element, doc):
        self.doc = doc
        self.source = options.get("input")
        self.toPNG = bool(options.get("png", True))
        self.toSVG = bool(options.get("svg", False))
        self.toPDF = True if doc.format in ["latex"] else bool(
            options.get("pdf", False))
        self.caption = options.get("caption", "Untitled")
        self.dir_to = options.get("directory", self.defaultdir_to)

        if os.path.exists(self.dir_to) != 1:
            os.mkdir(self.dir_to)

        self.counter = hashlib.sha1(data.encode("utf-8")).hexdigest()[:8]
        self.basename = "/".join([self.dir_to, str(self.counter)])

        if not self.source and data is not None:
            # pf.debug("not source and data is not None")
            self.source = ".".join([self.basename, "txt"])
            code = data
            open(self.source, "w", encoding="utf-8").write(data)
        else:  # source and data is "dont care"
            code = open(self.source, "r", encoding="utf-8").read()

        assert self.source is not None, "option input is mandatory"
        assert isinstance(self.toPNG, bool), "option png is boolean"
        assert isinstance(self.toPDF, bool), "option pdf is boolean"

        self.svg = ".".join([self.basename, "svg"])
        self.png = ".".join([self.basename, "png"])
        self.pdf = ".".join([self.basename, "pdf"])
        aafigure.render(code, self.svg, {"format": "svg"})

        if (self.toPDF):
            aafigure.render(code, self.pdf, {"format": "pdf"})

        if (self.toPNG):
            aafigure.render(code, self.png, {"format": "png"})

        # options = {
        #     "format": filetype,
        # }
        if self.doc.format in ["latex"]:
            linkto = self.pdf
        elif self.doc.format in ["html", "html5"]:
            linkto = self.svg
        else:
            if not (self.toPNG):
                aafigure.render(code, self.png, {"format": "png"})
            linkto = self.png

        caption = pf.convert_text(self.caption)
        caption = caption[0]
        caption = caption.content

        render_message = " ".join(["generate aafigure from", linkto])
        self.render_message = render_message if not self.render_message else " ".join(
            [self.render_message, linkto])
        pf.debug(self.render_message)
        element.classes.remove("aafigure")
        linkto = os.path.abspath(linkto).replace("\\", "/")
        img = pf.Image(*caption,
                       classes=element.classes,
                       url=linkto,
                       identifier=element.identifier,
                       title="fig:",
                       attributes=element.attributes)
        # pf.debug(img)
        ans = pf.Para(img)
        # pf.debug(ans)

        return ans
Beispiel #15
0
print ascii_art
# Parse the image.
aaimg = aafigure.AsciiArtImage(ascii_art)
aaimg.recognize()

# For fun, output the ASCII version in the console.
print " output ".center(78, '=')
aav = aafigure.aa.AsciiOutputVisitor({'file_like':sys.stdout, 'scale':2})
aav.visit_image(aaimg)
print "="*78

# Writing an SVG file would be possible in a similar way, but there is the much
# easier render function for that.

# A stringIO object is returned for the output when the output parameter is not
# given. If it were, the output would be directly written to that object.
visitor, output = aafigure.render(ascii_art, options={'format':'svg'})

# The process method can be used for a lower level access. The visitor class
# has to be specified by the user in this case.  To get output, a file like
# object has to be passed in the options:
# {'file_like' = open("somefile.svg", "wb")}
import aafigure.svg
import StringIO
fl = StringIO.StringIO()
visitor = aafigure.process(
    ascii_art,
    aafigure.svg.SVGOutputVisitor,
    options={'file_like': fl}
)
Beispiel #16
0
 def test_render_api_pdf(self):
     visitor, output = aafigure.render(ascii_art, options={'format': 'pdf'})
     self.assertTrue(b'%PDF' in output.getvalue())
Beispiel #17
0
 def test_render_api_svg(self):
     visitor, output = aafigure.render(ascii_art, options={'format': 'svg'})
     self.assertTrue(b'<svg' in output.getvalue())
Beispiel #18
0
# Show what we're parsing.
print " input ".center(78, '=')
print ascii_art
# Parse the image.
aaimg = aafigure.AsciiArtImage(ascii_art)
aaimg.recognize()

# For fun, output the ASCII version in the console.
print " output ".center(78, '=')
aav = aafigure.aa.AsciiOutputVisitor({'file_like': sys.stdout, 'scale': 2})
aav.visit_image(aaimg)
print "=" * 78

# Writing an SVG file would be possible in a similar way, but there is the much
# easier render function for that.

# A stringIO object is returned for the output when the output parameter is not
# given. If it were, the output would be directly written to that object.
visitor, output = aafigure.render(ascii_art, options={'format': 'svg'})

# The process method can be used for a lower level access. The visitor class
# has to be specified by the user in this case.  To get output, a file like
# object has to be passed in the options:
# {'file_like' = open("somefile.svg", "wb")}
import aafigure.svg
import StringIO
fl = StringIO.StringIO()
visitor = aafigure.process(ascii_art,
                           aafigure.svg.SVGOutputVisitor,
                           options={'file_like': fl})