示例#1
0
    def read_svg(self, file_path):
        with open(file_path, 'r') as f:
            svg = f.read()

        img = cairosvg.svg2png(bytestring=svg.encode('utf-8'))
        img = Image.open(io.BytesIO(img))
        s = np.array(img)[:,:,3].astype(np.float) # / 255.0
        max_intensity = np.amax(s)
        if max_intensity == 0:            
            return s, 0, []
        s = s / max_intensity

        path_list = []        
        num_paths = svg.count('polyline')

        for i in range(1,num_paths+1):
            svg_xml = et.fromstring(svg)
            svg_xml[1] = svg_xml[i]
            del svg_xml[2:]
            svg_one = et.tostring(svg_xml, method='xml')

            # leave only one path
            y_png = cairosvg.svg2png(bytestring=svg_one)
            y_img = Image.open(io.BytesIO(y_png))
            path = (np.array(y_img)[:,:,3] > 0)            
            path_list.append(path)

        return s, num_paths, path_list
示例#2
0
def exportsvg(inputDir, exportType, outputDir):
    if not os.path.exists(outputDir):
        os.mkdir(outputDir)
    num = 0
    for a,f,c in os.walk(inputDir):
        for fileName in c:
            path = os.path.join(a, fileName)
            if os.path.isfile(path) and fileName.endswith('.svg'):
                num += 1
                fileHandle = open(path)
                svg = fileHandle.read()
                fileHandle.close()
                exportPath = os.path.join(outputDir, fileName[:-3] + exportType)
                exportFileHandle = open(exportPath, 'w')

                if exportType == "png":
                    try:
                        cairosvg.svg2png(bytestring=svg, write_to=exportPath)
                    except:
                        print "error in convert svg file : %s to png."%(path)

                elif exportType == "pdf":
                    try:
                        cairosvg.svg2pdf(bytestring=svg, write_to=exportPath)
                    except:
                        print "error in convert svg file: %s to pdf."%(path)

                exportFileHandle.close()
                print "Success Export ", exportType, " -> ", exportPath

    print num, " files are tranformed from svg to ", exportType
示例#3
0
    def convert_to_png(input_file, output_file, width=None, height=None):
        """Convert svg to png."""
        if width and height:
            handle = Rsvg.Handle()
            svg = handle.new_from_file(input_file)
            dim = svg.get_dimensions()

            img = ImageSurface(FORMAT_ARGB32, width, height)
            ctx = Context(img)
            ctx.scale(width / dim.width, height / dim.height)
            svg.render_cairo(ctx)

            png_io = BytesIO()
            img.write_to_png(png_io)
            with open(output_file, 'wb') as fout:
                fout.write(png_io.getvalue())
            fout.close()
            svg.close()
            png_io.close()
            img.finish()
        else:
            with open(input_file, "r") as content_file:
                svg = content_file.read()
            content_file.close()
            fout = open(output_file, "wb")
            svg2png(bytestring=bytes(svg, "UTF-8"), write_to=fout)
            fout.close()
def single_flake_png(path, string):
    fullpath = path + string + ".svg"
    pngpath = path + string + ".png"
    single_flake(path, string)
    #Convert the svg to PNG
    import cairosvg
    cairosvg.svg2png(url=fullpath, write_to=pngpath)
示例#5
0
def serve_content(svgFile=None):
    output = ''
    try:
        with open(os.path.join(app.root_path, 'roadmap.svg'), 'r') as file_obj:
            for oneline in file_obj:
                stringindex = oneline.find('<g')
                if stringindex == -1:
                    output += oneline
                    continue
                stringindex = oneline.find('id')
                if stringindex == -1:
                    output += oneline
                    continue
                tempstring = oneline[stringindex:]
                randomint = random.randint(0, len(colorlist)-1)
                onelist = oneline.split(' ')
                outputstr = onelist[0] + ' ' + onelist[1] + ' ' + 'fill=' + colorlist[randomint] + '>\n'
                output += outputstr
    
        with open(os.path.join(app.root_path, 'images/test.png'), 'wb') as file_output:
            cairosvg.svg2png(output, write_to=file_output)
        
        with open(os.path.join(app.root_path, 'images/test.png')) as f:
            response = make_response(f.read())
            response.headers['Content-Type'] = 'image/png'
            return response
    except:
        abort(make_response("dumped", 400))
示例#6
0
    def read_svg(self, file_path):
        with open(file_path, 'r') as f:
            svg = f.read()

        svg = svg.format(w=self.width, h=self.height)
        img = cairosvg.svg2png(bytestring=svg.encode('utf-8'))
        img = Image.open(io.BytesIO(img))
        s = np.array(img)[:,:,3].astype(np.float) # / 255.0
        max_intensity = np.amax(s)
        s = s / max_intensity

        path_list = []        
        svg_xml = et.fromstring(svg)
        num_paths = len(svg_xml[0])

        for i in range(num_paths):
            svg_xml = et.fromstring(svg)
            svg_xml[0][0] = svg_xml[0][i]
            del svg_xml[0][1:]
            svg_one = et.tostring(svg_xml, method='xml')

            # leave only one path
            y_png = cairosvg.svg2png(bytestring=svg_one)
            y_img = Image.open(io.BytesIO(y_png))
            path = (np.array(y_img)[:,:,3] > 0)            
            path_list.append(path)

        return s, num_paths, path_list
示例#7
0
    def convert_svg_to_png(self):
        svg_files = glob(join(current_app.config['STATIC_PATH'], 'images',
                              'cards', '*.svg'))

        for svg_file in svg_files:
            png_file = svg_file.replace('.svg', '.png')
            svg2png(url=svg_file, write_to=png_file, width=2800, height=1500)
示例#8
0
def cairosvg_svg_to_png(svg, dir_path, page_id):
    fout = open("%s/%d_thumbnail.png"%(dir_path,page_id),'wb')
    try:
        cairosvg.svg2png(bytestring=bytes(svg,'utf-8'),write_to=fout)
    except:
        logger.error(svg)
        traceback.print_exc()
    fout.close()
def prerendered_html_to_image(html, name, path=None):

    if path is not None:
        name = os.path.join(path, name)

    logger.info(name)
    svg = extract_svg(html)
    cairosvg.svg2png(bytestring=svg, write_to=name)
    return svg[:10]
示例#10
0
def svg2png_cli():

    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument('inputfiles', nargs="+")
    ap.add_argument('--target', default='png', help="Target file/filetype.")
    argns = ap.parse_args()
    for input_fn in argns.inputfiles:
        svg2png(input_fn, target=argns.target)
示例#11
0
文件: drawer.py 项目: boopr/Trekke
def save_image_to_png(path):
    try:
        import cairosvg
    except Exception as e:
        print("Vous devez installer 'cairosvg' pour pouvoir enregistrer votre image.")
        print("Pour en savoir plus : http://cairosvg.org/")
        exit(0)

    cairosvg.svg2png(url='{}.svg'.format(OUTPUT_NAME), write_to=path)
def writeFilesForSVG(svgstring, battle):
        f = open(os.path.expanduser('~/battles/results/' + battle + 'graphic.svg'), 'w')
        f.write(svgstring)
        f.close()
        
        fout = open(os.path.expanduser('~/battles/results/' + battle + 'graphic.png'), 'wb')
        cairosvg.svg2png(bytestring=svgstring.encode('utf-8'),write_to=fout)

        fout.close()
示例#13
0
    def debug_and_draw(self, X, masks_idx, output_dir, show_notebook=False,
                       n=None):
        def encode64_png(np_array):
            output = io.BytesIO()
            scipy.misc.toimage(np_array).save(output, format='PNG')
            return base64.b64encode(output.getvalue())

        def make_image(elem: et.Element, np_array):
            elem.tag = '{http://www.w3.org/2000/svg}image'
            arr_base64 = encode64_png(np_array)
            elem.set('{http://www.w3.org/1999/xlink}href', "data:image/png;base64," +
                     arr_base64.decode('utf-8'))

        def set_text(elem: et.Element, text):
            children = list(elem)
            for c in children:
                elem.remove(c)
            elem.text = str(text[0])

        if n is None:
            n = len(X)

        outputs = self.debug(X, masks_idx)
        output_dict = dict(zip(self.debug_labels, outputs))
        d_out_real = {"d64_real": "charlie_d",
                      "d32_real": "bravo_d",
                      "d16_real": "alfa_d"}
        d_out_fake = {"d64_fake": "charlie_d",
                      "d32_fake": "bravo_d",
                      "d16_fake": "alfa_d"}

        for i in range(n):
            with open('lapgan.svg') as f:
                tree = et.parse(f)

            labels = self.debug_labels
            for elem in tree.iter():
                id = elem.get('id')
                if id is not None:
                    id = id.split("XXX")[0]
                if id in labels:
                    index = labels.index(id)
                    make_image(elem, outputs[index][i, 0])
                if id in list(d_out_real.keys()):
                    index = labels.index(d_out_real[id])
                    set_text(elem, outputs[index][i])
                if id in list(d_out_fake.keys()):
                    index = labels.index(d_out_fake[id])
                    set_text(elem, outputs[index][i+self.batch_size//2])

            svg_code = et.tostring(tree.getroot())
            fname = output_dir + "/{}.png".format(i)
            cairosvg.svg2png(bytestring=svg_code, write_to=fname)
            if show_notebook:
                import IPython.display
                IPython.display.Image(filename=fname)
示例#14
0
def str2png(svg_str, out_file):
	u'''
		SVG 文字列を PNG ファイルへ出力する
	'''
	global svg_header

	svg = svg_header + svg_str + '</svg>'

	#print svg
	cairosvg.svg2png(bytestring=svg,write_to=out_file)
def render_weather(bg):
    weather_svg = fetch_weather_svg()

    img_io = BytesIO()
    svg2png(bytestring=weather_svg, write_to=img_io)
    img_io.seek(0)

    img = Image.open(img_io)

    # Add a white background
    bg.paste(img, img)
示例#16
0
def rasterize_svgfiles(svgfiles):
    """
    Converts multiple svg files to png files with same basename.
    """

    for svgfile in svgfiles:
        output_dir = os.path.dirname(svgfile)
        name = os.path.basename(svgfile)
        (root, ext) = os.path.splitext(name)
        subprocess.call(["svgo", "-i", svgfile, "-o", svgfile], shell=False)
        cairosvg.svg2png(url=svgfile, write_to=os.path.join(output_dir, "{0}.png".format(root)))
示例#17
0
def preprocess_path(file_path, w, h, rng):
    with open(file_path, 'r') as f:
        svg = f.read()

    img = cairosvg.svg2png(bytestring=svg.encode('utf-8'))
    img = Image.open(io.BytesIO(img))
    s = np.array(img)[:,:,3].astype(np.float) # / 255.0
    max_intensity = np.amax(s)
    if max_intensity == 0:
        x = np.zeros([h, w, 2])
        y = np.zeros([h, w, 1])
        return x, y
    s = s / max_intensity

    while True:
        svg_xml = et.fromstring(svg)
        num_paths = svg.count('polyline')
        path_id = rng.randint(1,num_paths+1)
        svg_xml[1] = svg_xml[path_id]
        del svg_xml[2:]
        svg_one = et.tostring(svg_xml, method='xml')

        # leave only one path
        y_png = cairosvg.svg2png(bytestring=svg_one)
        y_img = Image.open(io.BytesIO(y_png))
        y = np.array(y_img)[:,:,3].astype(np.float) / max_intensity # [0,1]

        pixel_ids = np.nonzero(y)
        # assert len(pixel_ids[0]) > 0, '%s: no stroke px' % file_path
        if len(pixel_ids[0]) > 0:
            break

    # select arbitrary marking pixel
    point_id = rng.randint(len(pixel_ids[0]))
    px, py = pixel_ids[0][point_id], pixel_ids[1][point_id]

    y = np.reshape(y, [h, w, 1])
    x = np.zeros([h, w, 2])
    x[:,:,0] = s
    x[px,py,1] = 1.0

    # # debug
    # plt.figure()
    # plt.subplot(221)
    # plt.imshow(img)
    # plt.subplot(222)
    # plt.imshow(s, cmap=plt.cm.gray)
    # plt.subplot(223)
    # plt.imshow(np.concatenate((x, np.zeros([h, w, 1])), axis=-1))
    # plt.subplot(224)
    # plt.imshow(y[:,:,0], cmap=plt.cm.gray)
    # plt.show()

    return x, y
示例#18
0
    def toPNG(self):
        # first set environment variables b/c of cairo bug:
        import os
        os.environ['LANG'] = 'en_US.UTF-8'
        os.environ['LC_ALL'] = 'en_US.UTF-8'

        # then import cairosvg:
        #print(self.acetate_path)
        import cairosvg
        cairosvg.svg2png(url=self.svg_path,
            write_to=self.acetate_path
        )
示例#19
0
def saveImg():
    save = str(raw_input("Would you like to save this image?(Y/N)\n"))
    if save.upper() == "Y":
        turtle.hideturtle()
        name = str(raw_input("What would you like to name it? \n"))
        nameSav = name + ".svg"
        if os.path.isdir("Automaton Drawings") == False:
            os.mkdir("Automaton Drawings")
        os.chdir("Automaton Drawings")
        ts = turtle.getscreen().getcanvas()
        canvasvg.saveall(nameSav, ts)
        cairosvg.svg2png(url=nameSav, write_to=name + ".png")
def buildThumbnail(filename):
    (base, ext) = os.path.splitext(filename)
    if (ext == '.svg'):
        png = filename + '.png'
        if os.path.exists(filename):
            f = open(filename, 'r')
            fout = open(png, 'wb')
            cairosvg.svg2png(file_obj = f, write_to = fout, dpi = 19)
            f.close()
            fout.close()
        return(png)
    return(None)
示例#21
0
    def read_svg(self, file_path):
        with open(file_path, 'r') as f:
            svg = f.read()

        r = 0
        s = [1, -1]
        t = [0, -900]
        # if transform:
        #     r = rng.randint(-45, 45)
        #     # s_sign = rng.choice([1, -1], 1)[0]
        #     s_sign = -1
        #     s = 1.75 * rng.random_sample(2) + 0.25 # [0.25, 2)
        #     s[1] = s[1] * s_sign
        #     t = rng.randint(-100, 100, 2)
        #     if s_sign == 1:
        #         t[1] = t[1] + 124
        #     else:
        #         t[1] = t[1] - 900

        svg = svg.format(w=self.width, h=self.height, r=r, sx=s[0], sy=s[1], tx=t[0], ty=t[1])
        img = cairosvg.svg2png(bytestring=svg.encode('utf-8'))
        img = Image.open(io.BytesIO(img))
        s = np.array(img)[:,:,3].astype(np.float) # / 255.0
        max_intensity = np.amax(s)
        s = s / max_intensity

        path_list = []        
        svg_xml = et.fromstring(svg)

        sys_name = platform.system()
        if sys_name == 'Windows':
            num_paths = len(svg_xml[0]._children)
        else:
            num_paths = len(svg_xml[0])

        for i in range(num_paths):
            svg_xml = et.fromstring(svg)

            if sys_name == 'Windows':
                svg_xml[0]._children = [svg_xml[0]._children[i]]
            else:
                svg_xml[0][0] = svg_xml[0][i]
                del svg_xml[0][1:]
            svg_one = et.tostring(svg_xml, method='xml')

            # leave only one path
            y_png = cairosvg.svg2png(bytestring=svg_one)
            y_img = Image.open(io.BytesIO(y_png))
            path = (np.array(y_img)[:,:,3] > 0)            
            path_list.append(path)

        return s, num_paths, path_list
示例#22
0
 def _get_ethiquette_spider_chart(self, cr, uid, ids, field_name, arg, context=None):
     """Return image for the field 'ethiquette_spider_chart' depending of ethiquette_xxx values"""
     res = {}
     for product in self.browse(cr, uid, ids, context):
         codeSVG = grap_ethiquette_radar.CodeSVG%{
             'y_social': 105 - (15* int(product.ethiquette_social)),
             'x_organic': 105 + (15* int(product.ethiquette_organic)),
             'y_packaging': 105 + (15* int(product.ethiquette_packaging)),
             'x_local': 105 - (15* int(product.ethiquette_local)),
             }   
         output = StringIO.StringIO()
         cairosvg.svg2png(bytestring=codeSVG,write_to=output)
         res[product.id] = base64.b64encode(output.getvalue())
     return res
示例#23
0
def svg2img():
    svg_code = """
        <svg xmlns="http://www.w3.org/2000/svg" width="1625" height="814">
            <g transform="translate(19.48441247002388,178.6258652637545) scale(1586.0311750599524) rotate(0)">
            <path stroke="#37946e" stroke-alignment="inner" fill="none" id="MAIN_0" stroke-width="0.03" stroke-linecap="round" opacity="1" mask="url(#eraser_2)" d="M0.5852174165288777,0.07800307487018826C0.5942457382105804,0.07630222686353572,0.604320289308541,0.07315967085351822,0.6291822585791779,0.06936443013372785C0.6540442278498148,0.06556918941393748,0.7006294781423144,0.05889536738897108,0.7343892321526992,0.05523163055144606C0.7681489861630841,0.05156789371392104,0.8040002320656746,0.049213394057184855,0.8317407826414875,0.04738200910857773C0.8594813332173005,0.04555062415997061,0.888008973206084,0.0450284763921523,0.9008325356075769,0.044243320859803315"></path>
            </g>
            </svg>
    """

    svg2png(bytestring=svg_code, write_to='output.png')
    im = imageio.imread('output.png')
    bmp = potrace.Bitmap(im)
    path = bmp.trace()
    return path
示例#24
0
def preprocess_overlap(file_path, w, h, rng):
    with open(file_path, 'r') as f:
        svg = f.read()

    img = cairosvg.svg2png(bytestring=svg.encode('utf-8'))
    img = Image.open(io.BytesIO(img))
    s = np.array(img)[:,:,3].astype(np.float) # / 255.0
    max_intensity = np.amax(s)
    if max_intensity == 0:
        x = np.zeros([h, w, 1])
        y = np.zeros([h, w, 1])
        return x, y
    s = s / max_intensity

    path_list = []        
    num_paths = svg.count('polyline')

    for i in range(1,num_paths+1):
        svg_xml = et.fromstring(svg)
        svg_xml[1] = svg_xml[i]
        del svg_xml[2:]
        svg_one = et.tostring(svg_xml, method='xml')

        # leave only one path
        y_png = cairosvg.svg2png(bytestring=svg_one)
        y_img = Image.open(io.BytesIO(y_png))
        path = (np.array(y_img)[:,:,3] > 0)            
        path_list.append(path)

    y = np.zeros([h, w], dtype=np.int)
    for i in range(num_paths-1):
        for j in range(i+1, num_paths):
            intersect = np.logical_and(path_list[i], path_list[j])
            y = np.logical_or(intersect, y)

    x = np.expand_dims(s, axis=-1)
    y = np.expand_dims(y, axis=-1)

    # # debug
    # plt.figure()
    # plt.subplot(131)
    # plt.imshow(img)
    # plt.subplot(132)
    # plt.imshow(s, cmap=plt.cm.gray)
    # plt.subplot(133)
    # plt.imshow(y[:,:,0], cmap=plt.cm.gray)
    # plt.show()

    return x, y
示例#25
0
    def read_svg(self, file_path):
        with open(file_path, 'r', encoding='utf-8') as f:
            svg = f.read()

        r = 0
        s = [1, 1]
        t = [0, 0]
        # if transform:
        #     r = rng.randint(-45, 45)
        #     # s_sign = rng.choice([1, -1], 1)[0]
        #     s_sign = 1
        #     s = 1.75 * rng.random_sample(2) + 0.25 # [0.25, 2)
        #     s[1] = s[1] * s_sign
        #     t = rng.randint(-10, 10, 2)
        #     if s_sign == -1:
        #         t[1] = t[1] - 109

        svg = svg.format(w=self.width, h=self.height, r=r, sx=s[0], sy=s[1], tx=t[0], ty=t[1])
        img = cairosvg.svg2png(bytestring=svg.encode('utf-8'))
        img = Image.open(io.BytesIO(img))
        s = np.array(img)[:,:,3].astype(np.float) # / 255.0
        max_intensity = np.amax(s)
        s = s / max_intensity

        path_list = []        
        pid = 0
        num_paths = 0
        while pid != -1:
            pid = svg.find('path id', pid + 1)
            num_paths = num_paths + 1
        num_paths = num_paths - 1 # uncount last one
        
        for i in range(num_paths):
            svg_one = svg
            pid = len(svg_one)
            for j in range(num_paths):
                pid = svg_one.rfind('path id', 0, pid)
                if j != i:
                    id_start = svg_one.rfind('>', 0, pid) + 1
                    id_end = svg_one.find('/>', id_start) + 2
                    svg_one = svg_one[:id_start] + svg_one[id_end:]

            # leave only one path
            y_png = cairosvg.svg2png(bytestring=svg_one.encode('utf-8'))
            y_img = Image.open(io.BytesIO(y_png))
            path = (np.array(y_img)[:,:,3] > 0)            
            path_list.append(path)

        return s, num_paths, path_list
def svg2png(xml, **params):
    size = len(SVG_XPATH(xml))
    if size > 0:
        start = time.time()
        for position, svg_img in enumerate(SVG_XPATH(xml)):
            str_image_name = "%s.png" % (str(SVG_MATH_ID_XPATH(svg_img)[0]))
            with open(os.path.join(params['png_dir'], str_image_name), 'wb') as f2:
                try :
                    cairosvg.svg2png(bytestring=etree.tostring(svg_img, with_tail=False),write_to=f2, dpi=200)
                except ZeroDivisionError:
                    print 'Division by zero in: ', str_image_name, ' (empty mathml)'
                except Exception as detail:
                    print "[PY_ERR] error in: ", str_image_name, '. ' + str(detail)
                    sys.exit(1)
    return xml
def generate_png( request ):
  import rsvg
  import cairo
  import cairosvg

  content = request.POST.get('svg_data')

  # Check if we have proper content first
  if ( content is not None ):
    # Fix the spaces etc and remove unwanted stuff from the content
    content = content.strip()
    content = content + "\n"

    #file_name="test"
    file_name="tree_map"

    #Now we want to write this to file
    svg_file = open( settings.DATA_FILES_PATH + "/" + file_name + ".svg", "w+" )
    svg_file.write( content )
    svg_file.close()

    # Read in the content
    svg_file = open( settings.DATA_FILES_PATH + "/" + file_name + ".svg", "r" )

    # Open up the file to be written to
    png_file = open( settings.DATA_FILES_PATH + "/" + file_name + ".png", "w+" )

    # Do the export
    cairosvg.svg2png( file_obj = svg_file, write_to = png_file )

    # Close the svg & png file
    svg_file.close()
    png_file.close()

    # Create the blank image surface
    #blank_surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, 750, 480 )

    # Get the context
    #ctx = cairo.Context( blank_surface )

    # Dump SVG data to the image context
    #handler = rsvg.Handle( data = content.encode("utf-8") )
    #handler.render_cairo( ctx )

    # Create the final png image
    #final_png = blank_surface.write_to_png( settings.DATA_FILES_PATH + "/" + file_name + ".png" )

  return HttpResponse( "Success" )
示例#28
0
def generate_score_files(num):
	for i in range(num):
		print "Generate page num",i
		datadir = "./meas/"
		if not os.path.exists(datadir):
			os.makedirs(datadir)
		filename = "./meas/"+"mono_44_"+str(i)
		s,durlist,chordlist = gen_score(1)
		#d = s.show('musicxml.png')
		#s.show()
		#s.write("lily.svg", filename)
		s.write("musicxml",filename+".xml")
		musescore_to_svg(filename)
		svg_file = filename + ".svg"
		png_file = filename + ".png"
		cairosvg.svg2png(url=svg_file,write_to=png_file)
示例#29
0
    def get(self, path=None):
        colours = json.load(open(os.path.join(self.get_template_path(),
                                              "colours.json")))

        def colour_by_id(arg, default):
            id_ = int(self.get_argument(arg, default))
            for colour in colours.get("colours", []):
                if colour.get("id") == id_:
                    return colour['colour']
            raise Exception("No such colour {}".format(id_))

        svg = self.render_string(
            "colours.svg",
            colour_one=colour_by_id("one", "4"),
            colour_two=colour_by_id("two", "4"),
            colour_three=colour_by_id("three", "4"),
            colour_letter=colour_by_id("letter", "5"),
            initial=self.get_argument("initial", ""))

        width = int(self.get_argument("w", 64))
        height = int(self.get_argument("h", 64))

        self.set_header("content-type", "image/png")
        self.write(cairosvg.svg2png(svg,  # @UndefinedVariable
                                    parent_width=width,
                                    parent_height=height))
示例#30
0
def node_apply_end(repo, node, duration=None, interactive=None, result=None, **kwargs):
    if environ.get('TERM_PROGRAM', None) != "iTerm.app" or not interactive:
        LOG.debug("skipping iTerm stats (wrong terminal)")
        return

    if not IMPORTS:
        LOG.error("failed to import dependencies of itermstats plugin")
        return

    css_file = NamedTemporaryFile(delete=False)
    css_file.write(".text-overlay { display: none; }")
    css_file.close()

    config = Config(
        height=150,
        style=STYLE,
        width=350,
    )
    config.css.append(css_file.name)

    chart = Pie(config)
    chart.add('correct', result.correct)
    chart.add('fixed', result.fixed)
    chart.add('skipped', result.skipped)
    chart.add('failed', result.failed)

    png_data = cairosvg.svg2png(bytestring=chart.render())
    png_data_b64 = b64encode(png_data)

    remove(css_file.name)

    print("\033]1337;File=inline=1:{}\007".format(png_data_b64))
示例#31
0
import numpy as np
import cairosvg
import tensorflow as tf
import matplotlib.pyplot as plt

#%%
svg_begin = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">\n'
rnd = lambda: np.random.randint(0, 101)
# path_str = f'\t<path fill="none" stroke="#ffffff" d="M {rnd()},{rnd()} Q {rnd()},{rnd()},{rnd()},{rnd()}" />\n'
path_str = '<path fill="none" stroke="#ffffff" d="M 20,50 Q 40,13, 54,44" />'
svg_end = '</svg>\n'

svg = ''.join([svg_begin, path_str, svg_end])
print('svg', svg)

img = cairosvg.svg2png(svg.encode('utf-8'))
img = tf.io.decode_jpeg(img, channels=1)
img = tf.squeeze(img)

img_points = np.transpose(np.array(img).nonzero())
print('img points', img_points.shape)

plt.rcParams['axes.facecolor'] = 'black'
plt.imshow(img)
plt.show()

#%%

curves = fitCurve(img_points, 0.5)
print(curves)
示例#32
0
def topng(svg_data):

    svg2png(bytestring=svg_data, write_to='output.png', scale=4.0)
#Python3 Code
import cairosvg
import os

loaddir = 'sketch_vis'
savedir = 'sketch_png'

with open('categories.txt') as file:
    for line in file:
        ipdir = os.path.join(loaddir, line.strip())
        opdir = os.path.join(savedir, line.strip())
        if not os.path.exists(opdir):
            os.mkdir(opdir)
        classfile = os.listdir(ipdir)
        for cfile in classfile:
            ipfilename = os.path.join(ipdir, cfile)
            sfile = cfile.split('.')[0] + '.png'
            opfilename = os.path.join(opdir, sfile)
            svg_code = ''
            with open(ipfilename) as forg:
                for oneline in forg:
                    svg_code += oneline.strip()
            cairosvg.svg2png(bytestring=svg_code, write_to=opfilename)
        print(line.strip() + ' Done......')
import boto3
import cairosvg

#Verify permissions are working
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
    print(bucket.name)

#read in a file of emoji names
with open('data/emoji_numbers_76.txt') as f:
    content = f.readlines()
#remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]

client = boto3.client('s3')
for _ in range(len(content)):
    emoji = content[_]
    emoji_file = 'twitter-emojis/svg-all/' + emoji + '.svg'
    emoji_png_file = emoji + '.png'
    image = cairosvg.svg2png(file_obj=open(emoji_file, "rb"), scale=2)
    response = client.put_object(ACL='public-read',
                                 Body=image,
                                 Bucket='gentle-persuader-emoji',
                                 Key=emoji_png_file)

#verify upload
for bucket in s3.buckets.all():
    for key in bucket.objects.all():
        print(key.key)
示例#35
0
            # skip hidden files
            if item2.startswith('.'):
                continue

            # reset the options
            options = {**defaultOptions, **testOptions}

            # filenames (input MEI and output SVG)
            meiFile = os.path.join(path1, item1, item2)
            name, ext = os.path.splitext(item2)
            svgFile = os.path.join(path2, item1, name + '.svg')
            pngFile = os.path.join(path2, item1, name + '.png')

            # parse the MEI file
            tree = ET.parse(meiFile)
            root = tree.getroot()
            # try to get the extMeta tag and load the options if existing
            meta = root.findtext(".//mei:meiHead/mei:extMeta", namespaces=ns)
            if (meta != None and meta != ''):
                print(meta)
                metaOptions = json.loads(meta)
                options = {**options, **metaOptions}

            tk.setOptions(json.dumps(options))
            tk.loadFile(meiFile)
            svgString = tk.renderToSVG(1)
            svgString = svgString.replace("overflow=\"inherit\"",
                                          "overflow=\"visible\"")
            ET.ElementTree(ET.fromstring(svgString)).write(svgFile)
            cairosvg.svg2png(bytestring=svgString, scale=2, write_to=pngFile)
示例#36
0
def display_F2_graphs(params,num_F2,pic_size,mol):
    orange = (255/255,165/255,0)
    green = (0,1,0)
    light_blue = (0,1,1)

    png_files =[]

    w_len = 1 
    stop_while = True
    while stop_while:
        
        h_len_min = int(num_F2/w_len)+int(np.mod(num_F2,w_len)>0)
        
        h_temp = pic_size[0]/w_len*h_len_min
        if(h_temp>pic_size[1]) :
            w_len = w_len+1
        else:
            stop_while = False
    h_len =  h_len_min
    molSize= (int(pic_size[0]/w_len),int(pic_size[0]/w_len))
    for bond_idx in range(0,h_len*w_len):
        
        
        if( bond_idx < mol.GetNumBonds()):
            
            bond = mol.GetBondWithIdx(bond_idx)
            keep_atoms = [bond.GetBeginAtomIdx()]
            keep_atoms.append( bond.GetEndAtomIdx())
            
            keep_atoms=keep_atoms+list( set( [neigh.GetIdx() for neigh in bond.GetEndAtom().GetNeighbors()]+ [neigh.GetIdx() for neigh in bond.GetBeginAtom().GetNeighbors()]))
            keep_atoms2 = set(keep_atoms)
            
            all_atoms = set(np.array(range(0,mol.GetNumAtoms())))
            remove = list(all_atoms -keep_atoms2)
            edmol = Chem.EditableMol(mol)
            remove.sort(reverse=True)
            for atom_idx in remove:
                edmol.RemoveAtom(int(atom_idx))
            
            
            for indx in range(0,len(keep_atoms)):
                keep_atoms[indx] = keep_atoms[indx] - np.sum((remove<np.ones_like(remove)*keep_atoms[indx])*1)
    
            edmol_mol = edmol.GetMol()

            highlight=[]
            colors={} 
            for idx in  keep_atoms:
                highlight.append(int(idx))
                colors[int(idx)] = light_blue
                
            colors[keep_atoms[0]] = (139/250,69/250,19/250)
            colors[keep_atoms[1]] = green
            
            highlightBonds=[]
            bond_colors ={}
            for idx in range(edmol_mol.GetNumBonds()):
                highlightBonds.append(int(idx))
                bond_colors[idx] = light_blue
            sym_bond = edmol_mol.GetBondBetweenAtoms(int(keep_atoms[0]),int(keep_atoms[1]))
            
            bond_colors[sym_bond.GetIdx()] = (0,0,1)
    
    
    
            
            img, svg = gen_img_svg_mol(edmol_mol,highlight=highlight,colors=colors,highlightBonds=highlightBonds,bond_colors=bond_colors,molSize= molSize)
            fp = BytesIO()
            png_files.append(fp)
    
            svg2png(bytestring=svg,write_to=fp,scale=1)
        else:
            fp = BytesIO()
            png_files.append(fp)
            
            
            image = Image.new('RGB', molSize, color = 'white')
            draw = ImageDraw.Draw(image)
            image.save(fp, 'PNG')
            
            
        
    imgs = [ PIL.Image.open(i) for i in png_files ]
    imgs_comb = []
    for y_idx in range(0,h_len):
        y_idx_list = png_files[y_idx*w_len:w_len+y_idx*w_len]
        imgs_comb.append( np.hstack( (np.asarray(PIL.Image.open(i) ) for i in y_idx_list ) ))
        
    imgs_comb = np.vstack(imgs_comb)
    
    imgs_comb = PIL.Image.fromarray( imgs_comb)
    imgs_comb_size = imgs_comb.size
    if(imgs_comb_size[0]!=pic_size[0]):
        fp = BytesIO()
        image = Image.new('RGB', (pic_size[0]-imgs_comb_size[0],imgs_comb_size[1]), color = 'white')
        draw = ImageDraw.Draw(image)
        image.save(fp, 'PNG')
        imgs_comb=( np.hstack( (np.asarray(i) for i in [imgs_comb,PIL.Image.open(fp)] ) ))
        
        imgs_comb = PIL.Image.fromarray( imgs_comb)
        imgs_comb_size = imgs_comb.size
    if(imgs_comb_size[1]!=pic_size[1]):
        fp = BytesIO()
        image = Image.new('RGB', (pic_size[0],pic_size[1]-imgs_comb_size[1]), color = 'white')
        draw = ImageDraw.Draw(image)
        image.save(fp, 'PNG')
        imgs_comb=( np.vstack( (np.asarray(i) for i in [imgs_comb,PIL.Image.open(fp)] ) ))
        imgs_comb = PIL.Image.fromarray( imgs_comb)
    fp = BytesIO()
    imgs_comb.save( fp,'PNG' )
    #display(PIL.Image.open(fp))
    #print(imgs_comb.size)
    '''   
                    
    imgs_comb = PIL.Image.fromarray( imgs_comb)
    display(imgs_comb)
    
    
                imgs_comb = np.hstack( (np.asarray( i ) for i in [imgs_comb,img] ) )
            imgs_comb = PIL.Image.fromarray( imgs_comb)
            display(imgs_comb)
            
            #os.remove(list_im[0])
            #os.remove(list_im[1])
            imgs_comb.save( 'gif_decode/gif_molx'+str(str(params['gif_idx']-1).zfill(6))+'.png' )
            params['gif_idx'] = params['gif_idx']-1
    '''
    return imgs_comb
示例#37
0
 def as_png(self, dpi=300):
     """
     :return:
     """
     return svg2png(bytestring=self.as_svg().decode("utf-8"), dpi=dpi)
示例#38
0
def sample():

    name = str(request.form['name'])
    address1 = str(request.form['address1'])
    address2 = str(request.form['address2'])
    phone = str(request.form['phone'])
    email = str(request.form['email'])

    import uuid
    uid = str(uuid.uuid4())
    eachone = uid + '.png'

    import datetime
    import time
    ts = time.time()
    sts = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    ################## Choosing Template ################################################################################
    img = Image.open("input.png")
    print("Input taken")
    #####################################################################################################################
    c, conn = connection()
    c.execute(
        """INSERT INTO registration (name,address1,address2,phone,email,created_at,cid)VALUES (%s,%s,%s,%s,%s,%s,%s)""",
        (name, address1, address2, phone, email, sts, uid))
    conn.commit()
    c.close()

    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(
        "/home/default/Downloads/Postman/resources/app/assets/fonts/OpenSans/AbhayaLibre-ExtraBold.ttf",
        60)
    draw.text((550, 150), name, (26, 176, 74), font=font)

    #Address line 1
    font = ImageFont.truetype(
        "/home/default/Downloads/Postman/resources/app/assets/fonts/OpenSans/OpenSans-Bold.ttf",
        36)
    draw.text((550, 210), address1, (123, 124, 117), font=font)

    img.save(eachone)
    #Address line 2
    font = ImageFont.truetype(
        "/home/default/Downloads/Postman/resources/app/assets/fonts/OpenSans/OpenSans-Bold.ttf",
        36)
    draw.text((550, 250), address2, (123, 124, 117), font=font)
    img.save(eachone)
    #Phone
    font = ImageFont.truetype(
        "/home/default/Downloads/Postman/resources/app/assets/fonts/OpenSans/OpenSans-Bold.ttf",
        36)
    draw.text((550, 290), "P: " + phone, (123, 124, 117), font=font)
    img.save(eachone)
    #Email
    font = ImageFont.truetype(
        "/home/default/Downloads/Postman/resources/app/assets/fonts/OpenSans/OpenSans-Bold.ttf",
        30)
    draw.text((550, 330), "Email: " + email, (123, 124, 117), font=font)
    #img.save('imgoutput.png') # added static
    img.save(eachone)
    print('output done')

    ################ End of Choosing Template ##########################################################################

    ################ Move file to static folder ########################################################################
    import shutil
    shutil.copy('/home/default/Desktop/eBusinessCard/' + eachone,
                '/home/default/Desktop/eBusinessCard/static/')
    ##############End Move file to static folder #######################################################################

    ############ QR Code generation ####################################################################################

    import pyqrcode
    url = pyqrcode.create('http://192.168.1.10:5000/file/' + eachone)
    url.svg('uca-url.svg', scale=8, background="white")  # Saving as SVG file
    url.eps('uca-url.eps', scale=2)

    ########### End of QR code generation ##############################################################################

    ########### Convert SVG to PNG #####################################################################################
    import cairosvg
    eachoneQR = 'QR' + uid + '.png'
    cairosvg.svg2png(url='uca-url.svg', write_to=eachoneQR)
    ########### End Convert SVG to PNG #################################################################################

    ################ Move file to static folder ########################################################################
    import shutil
    shutil.copy('/home/default/Desktop/eBusinessCard/' + eachoneQR,
                '/home/default/Desktop/eBusinessCard/static/')
    ##############End Move file to static folder #######################################################################

    filename = 'static/' + eachoneQR
    filename2 = 'static/' + eachone
    #return render_template('download.html')
    # return render_template('idcard.html', value=filename, value2=filename2)
    return render_template('carddownload.html',
                           value=filename,
                           value2=filename2)
示例#39
0
def index():
    data = request.data
    ret = cairosvg.svg2png(bytestring=data)
    return send_file(io.BytesIO(ret), mimetype='image/png')
示例#40
0
 def render_png(self, request):
     svg_data = self.make_svg(request)
     return cairosvg.svg2png(bytestring=svg_data)
示例#41
0
 def fromSvgToFile(svgData, outFile):
     cairosvg.svg2png(bytestring=svgData, write_to=outFile)
     return Raster(None, pngFile=outFile)
示例#42
0
)

input_move = tkinter.Entry(input_frame)

head.grid(column=0, row=0)
game.grid(column=0, row=1)
input_frame.grid(column=0, row=4)
suggest.pack(side=tkinter.LEFT)
input_move.pack(side=tkinter.LEFT)

chessboard_game.push(pgn_data[i]["Moves"][j])

svg_img = chess.svg.board(board=chessboard_game,
                          lastmove=pgn_data[i]["Moves"][j],
                          size=600)
png_img = cairosvg.svg2png(bytestring=svg_img)
im = PIL.Image.open(io.BytesIO(png_img))
photo = PIL.ImageTk.PhotoImage(im)

img = tkinter.Label(window, image=photo, text=pgn_data[i]["Text"])

img.grid(column=0, row=2, padx=20, pady=20)

j += 1

print(len(pgn_data[i]["Moves"]))


def prev_comm():
    global i
    if i > 0:
示例#43
0
 def _render_board(self, board, size):
     s = chess.svg.board(board,
                         size=size,
                         coordinates=randint(0, 1),
                         orientation=randint(0, 1))
     return svg2png(bytestring=s)
示例#44
0
def display_F1_graphs(params,num_F1,display_F1,flash_F1,pic_size,atoms, NN_Tensor):
    orange = (255/255,165/255,0)
    green = (0,1,0)
    light_blue = (0,1,1)
   


    png_files =[]
    
                    
    
    w_len = 1 
    stop_while = True
    while stop_while:
        
        h_len_min = int(num_F1/w_len)+int(np.mod(num_F1,w_len)>0)
        
        h_temp = pic_size[0]/w_len*h_len_min
        if(h_temp>pic_size[1]) :
            w_len = w_len+1
        else:
            stop_while = False
    h_len =  h_len_min
    molSize= (int(pic_size[0]/w_len),int(pic_size[0]/w_len))
    for atom_idx in range(0,h_len*w_len):
        if( atom_idx < len(atoms)and np.sum(atoms[atom_idx])!=0 and display_F1[atom_idx]==1):
            edmol = MolFromSmiles('')
            edmol = Chem.EditableMol(edmol)
            
            
            atom_feature_num = np.argmax(atoms[atom_idx])
            if(params['atoms'][atom_feature_num]=='H'):
                mol = Chem.MolFromSmiles('[H]')
            else:
                mol = Chem.MolFromSmiles(params['atoms'][atom_feature_num])
            atom = mol.GetAtomWithIdx(0)
            edmol.AddAtom(atom)
            if(flash_F1[atom_idx]==1):
                bond_colour = (0,0,1)
                atom_colour = (0,1,0)
            else:
                bond_colour = light_blue
                atom_colour = green
            highlight=[0]
            colors={0:atom_colour} 
            highlightBonds=[]
            bond_colors={}
            for edge_idx in range(0,len(NN_Tensor[0]))  :  
                sparse_NN_feature = np.argmax(NN_Tensor[atom_idx][edge_idx])
                if(sparse_NN_feature!=0):
                    atom_NN, bond_NN = atom_bond_from_sparse_NN_feature(sparse_NN_feature-1,params)
                    edmol.AddAtom(atom_NN)
                    #edmol.AddAtom(MolFromSmiles('I').GetAtomWithIdx(0))
                    edmol.AddBond(edge_idx+1,0,bond_NN)
                    highlightBonds.append(edge_idx)
                    bond_colors[edge_idx] = bond_colour
                    highlight.append(edge_idx+1)
                    colors[edge_idx+1]= bond_colour
                    
    
            mol = edmol.GetMol()
            
            img, svg = gen_img_svg_mol(mol,highlight=highlight,colors=colors,highlightBonds=highlightBonds,bond_colors=bond_colors,molSize= molSize)
            fp = BytesIO()
            png_files.append(fp)
    
            svg2png(bytestring=svg,write_to=fp,scale=1)
        else:
            fp = BytesIO()
            png_files.append(fp)
            
            
            image = Image.new('RGB', molSize, color = 'white')
            draw = ImageDraw.Draw(image)
            image.save(fp, 'PNG')
            
            
        
    imgs = [ PIL.Image.open(i) for i in png_files ]
    imgs_comb = []
    for y_idx in range(0,h_len):
        y_idx_list = png_files[y_idx*w_len:w_len+y_idx*w_len]
        imgs_comb.append( np.hstack( (np.asarray(PIL.Image.open(i) ) for i in y_idx_list ) ))
        
    imgs_comb = np.vstack(imgs_comb)
    
    imgs_comb = PIL.Image.fromarray( imgs_comb)
    imgs_comb_size = imgs_comb.size
    if(imgs_comb_size[0]!=pic_size[0]):
        fp = BytesIO()
        image = Image.new('RGB', (pic_size[0]-imgs_comb_size[0],imgs_comb_size[1]), color = 'white')
        draw = ImageDraw.Draw(image)
        image.save(fp, 'PNG')
        imgs_comb=( np.hstack( (np.asarray(i) for i in [imgs_comb,PIL.Image.open(fp)] ) ))
        
        imgs_comb = PIL.Image.fromarray( imgs_comb)
        imgs_comb_size = imgs_comb.size
    if(imgs_comb_size[1]!=pic_size[1]):
        fp = BytesIO()
        image = PIL.Image.new('RGB', (pic_size[0],pic_size[1]-imgs_comb_size[1]), color = 'white')
        draw = PIL.ImageDraw.Draw(image)
        image.save(fp, 'PNG')
        imgs_comb=( np.vstack( (np.asarray(i) for i in [imgs_comb,PIL.Image.open(fp)] ) ))
        imgs_comb = PIL.Image.fromarray( imgs_comb)
    fp = BytesIO()
    imgs_comb.save( fp,'PNG' )
    #display(PIL.Image.open(fp))
    #print(imgs_comb.size)
    '''   
                    
    imgs_comb = PIL.Image.fromarray( imgs_comb)
    display(imgs_comb)
    
    
                imgs_comb = np.hstack( (np.asarray( i ) for i in [imgs_comb,img] ) )
            imgs_comb = PIL.Image.fromarray( imgs_comb)
            display(imgs_comb)
            
            #os.remove(list_im[0])
            #os.remove(list_im[1])
            imgs_comb.save( 'gif_decode/gif_molx'+str(str(params['gif_idx']-1).zfill(6))+'.png' )
            params['gif_idx'] = params['gif_idx']-1
    '''
    return imgs_comb
out = Path('gen/')
icons_out = Path(out, 'icons/')

if out.exists and out.is_dir():
    shutil.rmtree(str(out))

icons_out.mkdir(parents=True)

for f in sprite_files:
    element = etree.SubElement(files_element, 'file')
    element.text = f.as_posix()
    element.set('id', f.stem)

    element.set('name', (f.stem.replace('-', ' ')).title())

    icon_name = f.stem + '.png'
    element.set(
        'icon',
        icons_out.relative_to(out).joinpath(
            icon_name).as_posix())  # Pencil uses Unix-style paths for icons

    with open(os.path.join(str(icons_out), icon_name), 'wb+') as icon_out:
        thumb = cairosvg.svg2png(file_obj=str(f), write_to=icon_out)

stylesheet = etree.parse('stylesheet.xsl')
transform = etree.XSLT(stylesheet)

result = transform(files_element)

result.write(os.path.join(str(out), 'Definition.xml'), pretty_print=True)
示例#46
0
def svg2png(svg):
    # assume that 'cairosvg' exists
    import cairosvg
    cairosvg.svg2png(url=svg, write_to=svg[:-4] + '.png', dpi=250)
    return svg[:-4] + '.png'
示例#47
0
def main():
    #cairosvg.svg2png(url="/tmp/outfile3.svg", write_to="/tmp/output.png")
    msas, misas = fetch_cbsas()
    ordered = fetch_ordered_msas()
    #for idx in range(42):
    for idx, msa in enumerate(ordered):
        #if idx < 30:
        #    continue
        states = msa.split(', ')[1].split('-')
        if 'AK' in states or 'HI' in states:
            continue
        counties = msas[msa.replace('–', '--')]
        with open('/tmp/outfile2.svg') as f:
            soup = bs4.BeautifulSoup(f.read(), "lxml")
            svg = soup.svg
        ocean = svg.find('rect', attrs={'id': 'ocean'})
        cty_group = svg.find('g', attrs={'inkscape:label': 'counties'})
        d_paths = []
        paths = []
        county_set = set(counties)
        for tag in svg.find_all("path"):
            if tag['id'] in counties:
                path = svgpathtools.parse_path(tag['d'])
                d_paths.append(path)
                paths.append(tag)
                county_set.remove(tag['id'])
        if county_set:
            print('ERROR >>> {} {}'.format(county_set, msa))
        d_all = ' '.join(path.d() for path in d_paths)
        new_tag = soup.new_tag("path")
        new_tag['d'] = d_all
        new_tag['id'] = msa
        new_tag['stroke'] = '#29a449'
        new_tag['stroke-width'] = '2.0'
        new_tag['fill'] = 'none'
        path = svgpathtools.parse_path(d_all)
        bbox = path.bbox()
        bbox = (bbox[0], bbox[2], bbox[1] - bbox[0], bbox[3] - bbox[2])
        bbox = expand_bbox(bbox, 100, float(ocean['width']), float(ocean['height']))
        #raise Exception([x['id'] for x in canvas_min])
        viewbox = " ".join(str(x) for x in bbox)
        svg['viewBox'] = viewbox
        #157 302 500 500
        #svg['viewBox'] = "200 300 400 500"
        svg['height'] = 800
        svg['width'] = 800
        cty_group.append(new_tag)
        for path in paths:
            path['style'] = "clip-rule:evenodd;fill:#9fd08a;fill-opacity:1;fill-rule:evenodd;stroke:#999999;stroke-width:0.2;stroke-miterlimit:4;stroke-dasharray:none"
            cty_group.append(path)
        """
        start = paths[0]
        for path in paths[1:]:
            start = path_union(start, path)
        raise Exception(start)
        new_tag = soup.new_tag("path")
        print(dir(start))
        new_tag['d'] = start.d()
        new_tag['id'] = msa
        #svg.append(new_tag)
        """
        with open('/tmp/outfile3.svg', 'w') as f:
            f.write(svg.prettify())
        cairosvg.svg2png(url="/tmp/outfile3.svg", write_to="/tmp/{:03}.png".format(idx))
    """
def generate_chart_from_prometheus(run: Run, export_format: str):
    """
    Generate charts from probes that pulled data out of Prometheus. The charts
    are serialized to SVG (for HTML reports) and PNG (for PDF reports).
    """
    output = run.get("output")
    if not isinstance(output, dict):
        return

    data = output.get("data")
    if data:
        result_type = data.get("resultType")
        if result_type == "matrix":

            chart = pygal.Line(
                x_label_rotation=20, style=DefaultStyle, truncate_legend=-1,
                show_minor_x_labels=False, legend_at_bottom=True,
                legend_at_bottom_columns=1)

            # we may have series with different x length, so we try to
            # generate a set of all seen abscisses
            x = set([])
            for result in data["result"]:
                values = result.get("values")
                for value in values:
                    x.add(value[0])

            # now we have our range of abscissa, let's map those
            # timestamps to formatted strings
            x = sorted(list(x))
            fromts = datetime.utcfromtimestamp
            chart.x_labels = [
                fromts(v).strftime('%Y-%m-%d\n %H:%M:%S') for v in x]
            chart.x_labels_major = chart.x_labels[::10]
            chart.title = "Query -  {}".format(
                run["activity"]["provider"]["arguments"]["query"])

            for result in data["result"]:
                # initialize first to null values to handle missing data
                y = [None] * len(x)

                # next, we update the y with actual values
                values = result.get("values")
                for value in values:
                    x_idx = x.index(value[0])
                    y[x_idx] = int(value[1])

                metric = result["metric"]
                if "method" in metric:
                    y_label = "{m} {p} - {s}".format(
                        m=metric["method"], p=metric["path"],
                        s=metric["status"])
                elif "pod" in metric:
                    y_label = metric["pod"]
                else:
                    y_label = "_".join(
                        [v for k, v in metric.items() if k != '__name__'])
                chart.add(y_label, y, allow_interruptions=True)

            if export_format in ["html", "html5"]:
                run["charts"] = [chart.render(disable_xml_declaration=True)]
            else:
                run["charts"] = [
                    b64encode(
                        cairosvg.svg2png(bytestring=chart.render(), dpi=72)
                    ).decode("utf-8")
                ]
示例#49
0
 def _applySVG(self, img, svg_str):
     png_bytes = svg2png(svg_str)
     graphic = Image.open(io.BytesIO(png_bytes))
     img.paste(graphic)
示例#50
0
文件: games.py 项目: echau01/cs221bot
 def render_board(board: chess.Board) -> BytesIO:
     boardimg = chess.svg.board(board=board, lastmove=board.peek() if board.move_stack else None, check=board.king(turn) if board.is_check() or board.is_checkmate() else None, flipped=board.turn == chess.BLACK)
     res = BytesIO()
     svg2png(bytestring=boardimg, write_to=res)
     res.seek(0)
     return res
示例#51
0
文件: sql.py 项目: Lymia/rowboat
    def words_usage(self, event, word, unit='days', amount=7):
        sql = '''
            SELECT date, coalesce(count, 0) AS count
            FROM
                generate_series(
                    NOW() - interval %s,
                    NOW(),
                    %s
                ) AS date
            LEFT OUTER JOIN (
                SELECT date_trunc(%s, timestamp) AS dt, count(*) AS count
                FROM messages
                WHERE
                    timestamp >= (NOW() - interval %s) AND
                    timestamp < (NOW()) AND
                    guild_id=%s AND
                    (SELECT count(*) FROM regexp_matches(content, %s)) >= 1
                GROUP BY dt
            ) results
            ON (date_trunc(%s, date) = results.dt);
        '''

        msg = event.msg.reply(':alarm_clock: One moment pls...')

        start = time.time()
        tuples = list(Message.raw(
            sql,
            '{} {}'.format(amount, unit),
            '1 {}'.format(unit),
            unit,
            '{} {}'.format(amount, unit),
            event.guild.id,
            '\s?{}\s?'.format(word),
            unit
        ).tuples())
        sql_duration = time.time() - start

        start = time.time()
        chart = pygal.Line()
        chart.title = 'Usage of {} Over {} {}'.format(
            word, amount, unit,
        )

        if unit == 'days':
            chart.x_labels = [i[0].strftime('%a %d') for i in tuples]
        elif unit == 'minutes':
            chart.x_labels = [i[0].strftime('%X') for i in tuples]
        else:
            chart.x_labels = [i[0].strftime('%x %X') for i in tuples]

        chart.x_labels = [i[0] for i in tuples]
        chart.add(word, [i[1] for i in tuples])

        pngdata = cairosvg.svg2png(
            bytestring=chart.render(),
            dpi=72)
        chart_duration = time.time() - start

        event.msg.reply(
            '_SQL: {}ms_ - _Chart: {}ms_'.format(
                int(sql_duration * 1000),
                int(chart_duration * 1000),
            ),
            attachments=[('chart.png', pngdata)])
        msg.delete()
示例#52
0
for egg in range(len(eggs)):
    print("Creating QR code for egg " + str(egg))
    template = templates[eggs[egg]["template"]]

    dwg = svgwrite.Drawing(size=(template["bg_w"], template["bg_h"]))
    bg_img = dwg.image(template["bg_url"],
                       insert=(0, 0),
                       size=(template["bg_w"], template["bg_h"]))
    dwg.add(bg_img)

    qr_url = "http://www.crossroad.org.uk/easter/?egg=" + f'{egg:02}'
    fname = "./output/easter_" + f'{egg:02}' + ".png"

    qr_code = pyqrcode.create(qr_url)
    buffer = BytesIO()
    qr_code.svg(buffer, xmldecl=False, svgns=False, omithw=True)
    svg_str = buffer.getvalue().decode('utf-8')
    path_idx = svg_str.index(" d=\"")
    path_d = svg_str[path_idx + 4:-10]
    path = dwg.path(d=path_d, fill='black', stroke='black')
    path.translate(template["qr_x"], template["qr_y"])
    path.scale(template["qr_size"] / 45)
    dwg.add(path)
    font_style = "font-family:" + template["text_font"] + "; font-size:" + \
        str(template["text_size"]) + "pt; fill:" + template["text_color"]
    three_words = dwg.text("Code: " + eggs[egg]["three_words"], \
        insert=(template["text_x"], template["text_y"]), style=font_style)
    dwg.add(three_words)

    svg2png(bytestring=dwg.tostring(), write_to=fname)
示例#53
0
文件: gen.py 项目: imac01/cwg
def convert_svg_to_png(svg_path, png_path):
    quality = 100
    with open(svg_path, 'r') as f:
        svg_data = '\n'.join(f.readlines())
    svg2png(bytestring=svg_data, write_to=png_path, \
            width=quality, height=quality)
import os
import cv2
from io import BytesIO
import cairosvg
from PIL import Image

if __name__ == '__main__':
    for f in os.listdir('raw_icons/'):
        file_path = os.path.join('raw_icons', f)
        output_file_path = os.path.join('icons', os.path.splitext(f)[0] + ".png")

        if file_path.endswith('.svg'):
            out = BytesIO()
            cairosvg.svg2png(url=file_path, write_to=output_file_path)
            
            img = cv2.imread(output_file_path)
            h, w, _ = img.shape
            resized_img = cv2.resize(img, (128, 128 * h//w))
            
            cv2.imwrite(output_file_path, resized_img)
        else:                
            img = cv2.imread(file_path)
            h, w, _ = img.shape
            resized_img = cv2.resize(img, (128, 128 * h//w))
            
            cv2.imwrite(output_file_path, resized_img)
    
    print("Done!")

示例#55
0
    def png(self, **kwargs):
        import cairosvg

        return cairosvg.svg2png(bytestring=self.svg().encode(), **kwargs)
fig = sg.SVGFigure(
    Unit((fig1_width_size + fig2_width_size) - 360),
    Unit(min(fig1_height_size, fig2_height_size) - 50),
)

fig.append(
    [etree.Element("rect", {"width": "100%", "height": "100%", "fill": "white"})]
)

plot1 = fig1.getroot()
plot1.moveto(10, 30)

plot2 = fig2.getroot()
plot2.moveto(fig1_width_size - 160, 12)

text_A = sg.TextElement(10, 30, "A", size=22, weight="bold")
text_B = sg.TextElement(fig1_width_size - 160, 30, "B", size=22, weight="bold")

fig.append([plot1, plot2, text_A, text_B])
# -

# save generated SVG files
fig.save("output/figures/polka_filtered_background_panels.svg")
svg2png(
    bytestring=fig.to_str(),
    write_to="output/figures/polka_filtered_background_panels.png",
    dpi=600,
)
display(SVG(fig.to_str()))
示例#57
0
def save_svg2png(svg_filename, png_filename):
    svg2png(open(svg_filename, 'rb').read(), write_to=open(png_filename, 'wb'))
示例#58
0
 def fromSvg(svgData):
     pngData = cairosvg.svg2png(bytestring=svgData)
     return Raster(pngData)
示例#59
0
 def render_png(self, request):
     svg_data = self.make_svg(request)
     png_data = cairosvg.svg2png(bytestring=svg_data)
     return aiohttp.web.Response(body=png_data, content_type="image/png")
示例#60
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 = 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(),
        )

        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))