Exemplo n.º 1
0
    def __init__(self, file, max_width, outter=True):
        self.outter = outter

        svgf = svg.parse(file)
        a, b = svgf.bbox()
        width, height = (b - a).coord()
        svgf = svgf.translate(a).scale(max_width/width)
        a, b = svgf.bbox()

        self.width, self.height = (b - a).coord()

        self.points = []
        for el in svgf.flatten():
            expected_title = "outter" if self.outter else "inner"
            if el.title() != expected_title:
                continue

            #if self.outter:
            for segment in el.segments():
                self.points.extend([[f - g for f, g in zip(x.coord(), a.coord())] for x in segment])
            #else:
            #    for segment in el.segments():
            #        self.points.extend([[f - g for f, g in zip(x.coord(), a.coord())] for x in segment])

        self.points.sort(key=lambda x: x[0])
        self.cache = {}
Exemplo n.º 2
0
def draw_svg(svg_filename, centered=True):
    f = svg.parse(svg_filename)

    (min_point, max_point) = f.bbox()
    (width, height) = (min_point + max_point).coord()
    x_centering_adj = width / 2
    y_centering_adj = height / 2

    screen = turtle.Screen()
    turtles = []
    processes = []

    for item in f.flatten():
        if (hasattr(item, 'segments')):
            segments = item.segments(20)
            for segment in segments:
                print("doing a segment")
                turtles.append(turtle.Turtle())
                new_process = Process(target=draw_segment,
                                      args=(turtles[-1], segment,
                                            x_centering_adj, y_centering_adj))
                print("created process")
                new_process.start()
                print("started process")
                processes.append(new_process)
                print("added process to processes")

    for process in processes:
        process.join()

    screen.mainloop()
    input("waiting...")
Exemplo n.º 3
0
def draw_svg(svg_filename, centered=True):
    f = svg.parse(svg_filename)

    (min_point, max_point) = f.bbox()
    (width, height) = (min_point + max_point).coord()
    x_centering_adj = width / 2
    y_centering_adj = height / 2

    for item in f.flatten():
        if (hasattr(item, 'segments')):
            for segment in item.segments(20):
                x, y = segment[0].coord()

                if (centered):
                    x = x - x_centering_adj
                    y = y - y_centering_adj

                go_to_coord(x, y, False)

                for point in segment[1:]:
                    x, y = point.coord()

                    if (centered):
                        x = x - x_centering_adj
                        y = y - y_centering_adj

                    go_to_coord(x, y)

    go_to_coord(0, 0, False)
Exemplo n.º 4
0
    def __init__( self, file_name, module_name, module_value ):

        self.file_name = file_name
        self.module_name = module_name
        self.module_value = module_value

        print( "Parsing SVG..." )
        self.svg = svg.parse( file_name )
Exemplo n.º 5
0
    def __init__(self, file_name, module_name, module_value):

        self.file_name = file_name
        self.module_name = module_name
        self.module_value = module_value

        print("Parsing SVG...")
        self.svg = svg.parse(file_name)
Exemplo n.º 6
0
 def __init__(self, svgfile, fr, to, x0, y0):
     self.fr = fr
     self.to = to
     data = open(svgfile).read()
     paths = svg.parse(data)
     self.path = paths[0]
     self.path.fit(x=x0, y=y0)
     self.dt = 1 / float(to - fr)  # time unit
Exemplo n.º 7
0
def convert(source: str, dest: str):
    log.debug(f"Converting {source} in {dest}")
    image = svg.parse(source)
    bmim, bmax = image.bbox()
    max_y = bmax.y
    drawing = dxf.drawing(dest)

    def flipped_y(p):
        # pdf sizes @ 72 px/in -> mm
        return (p.x / 72 * 25.4, (max_y - p.y) / 72 * 25.4)

    for part in image.flatten():
        if hasattr(part, 'segments'):
            for segment in part.segments():
                drawing.add(dxf.polyline([flipped_y(p) for p in segment]))
        else:
            log.debug(f"Unsupported SVG element {type(part).__name__}")

    drawing.save()
Exemplo n.º 8
0
def import_svg(file_name, centered=False, position=Point.ZERO):
    """Import geometry from a SVG file."""
    # We defer loading the SVG library until we need it.
    # This makes creating a node faster.
    import svg
    if not file_name: return None
    f = file(file_name, 'r')
    s = f.read()
    f.close()
    g = Geometry()
    paths = svg.parse(s, True)
    for path in paths:
        g.add(path)
    t = Transform()
    if centered:
        x, y, w, h = list(g.bounds)
        t.translate(-x - w / 2, -y - h / 2)
    t.translate(position)
    g = t.map(g)
    return g
Exemplo n.º 9
0
def import_svg(file_name, centered=False, position=Point.ZERO):
    """Import geometry from a SVG file."""
    # We defer loading the SVG library until we need it.
    # This makes creating a node faster.
    import svg
    if not file_name: return None
    f = file(file_name, 'r')
    s = f.read()
    f.close()
    g = Geometry()
    paths = svg.parse(s, True)
    for path in paths:
        g.add(path)
    t = Transform()
    if centered:
        x, y, w, h = list(g.bounds)
        t.translate(-x-w/2, -y-h/2)
    t.translate(position)
    g = t.map(g)
    return g
Exemplo n.º 10
0
    def from_svg(self, svgfile, max_width=None, max_height=None):
        svgf = svg.parse(svgfile)
        a, b = svgf.bbox()
        width, height = (b - a).coord()

        if max_width:
            svgf = svgf.translate(a).scale(max_width / width)

        if max_height:
            svgf = svgf.translate(a).scale(max_height / height)

        a, b = svgf.bbox()

        for el in svgf.flatten():
            foo = []
            for segment in el.segments(.01):
                last = None
                for el in segment:
                    el = el.coord()
                    if last is None or el[0] != last[0] or el[1] != last[1]:
                        foo.append([f - g for f, g in zip(el, a.coord())])
                    last = el

            self.add(Line(foo))
Exemplo n.º 11
0
def new_parse_file(filename):
    try:
        f = open(filename, 'r')
    except:
        print("Illegal Filename")
        return False
    res = dict()
    s = svg.parse(filename)
    # for i in s.items:
    #     print(i)
    #     print(i.items)
    #     if hasattr(i, "style"): print(i.style)
    a, b = s.bbox()

    width, height = (a + b).coord()

    base = dict()
    base['width'] = float(width)
    base['height'] = float(height)
    base["rake_sizes"] = s.root.get("rake_sizes")
    if (s.root.get("scale_to_disp")):
        base['scale_for_disp'] = float(s.root.get("scale_for_disp"))
    else:
        base['scale_for_disp'] = None
    res = dict()
    res['svg_base'] = base
    res["elements"] = list()

    for i in s.flatten():
        if hasattr(i, "segments"):
            stroke = False
            startpoint = False
            stroke_width = 0
            if (i.get_style("stroke-width")
                    and i.get_style("stroke-width").val > 0
                    and i.get_style("stroke")):
                if i.get_style("stroke").val not in [
                        "none", "#ffffff", "#fff", "#ff0000", "#00ff00"
                ]:
                    stroke = True
                    stroke_width = i.get_style("stroke-width").val
                if i.get_style("stroke").val == "#00ff00":
                    startpoint = True
            coords = i.segments(precision=100)
            print("coords0", isinstance(coords[0], list), coords[0])
            if isinstance(coords[0], list):
                print(i.get_style("fill"))
                print("First elem list!")
                if i.closed:
                    j = 0
                    holes = list()
                    for l_coords in coords:
                        if j == 0:
                            lc = remove_adjacent(l_coords, True)
                            if signed_area(lc) > 0:
                                lc.reverse()
                        else:
                            hc = l_coords
                            # if signed_area(hc) < 0:
                            hc.reverse()
                            hc = remove_adjacent(hc, True)
                            holes.append(hc)
                        j = j + 1
                    res["elements"].append({
                        "closed":
                        i.closed,
                        "filled":
                        i.get_style("fill").val
                        not in ["none", "#fff", "#ffffff", None],
                        "stroke":
                        stroke,
                        "startpoint":
                        startpoint,
                        "manually_modified":
                        "manually_modified" in i.attributes,
                        "stroke_width":
                        stroke_width,
                        "rake_states":
                        [j for j in i.attributes.get("rake_info").split(" ")]
                        if i.attributes.get("rake_info") else None,
                        "coords":
                        lc,
                        "holes":
                        holes
                    })
                else:
                    for l_coords in coords:
                        if i.closed and signed_area(l_coords) > 0:
                            print("signed area  > 0")
                            l_coords.reverse()
                            # elements are holes!
                        print("LCOORDS: ", l_coords)
                        res["elements"].append({
                            "closed":
                            i.closed,
                            "filled":
                            i.get_style("fill").val
                            not in ["none", "#fff", "#ffffff", None],
                            "stroke":
                            stroke,
                            "startpoint":
                            startpoint,
                            "manually_modified":
                            "manually_modified" in i.attributes,
                            "stroke_width":
                            stroke_width,
                            "rake_states": [
                                j for j in i.attributes.get("rake_info").split(
                                    " ")
                            ] if i.attributes.get("rake_info") else None,
                            "coords":
                            l_coords,
                            "holes":
                            list()
                        })
            else:
                if i.closed and signed_area(coords) > 0:
                    print("signed area  > 0")
                    coords.reverse()

                res["elements"].append({
                    "closed":
                    i.closed,
                    "filled":
                    i.get_style("fill").val
                    not in ["none", "#fff", "#ffffff", None],
                    "stroke":
                    stroke,
                    "startpoint":
                    startpoint,
                    "manually_modified":
                    "manually_modified" in i.attributes,
                    "stroke_width":
                    stroke_width,
                    "rake_states":
                    [j for j in i.attributes.get("rake_info").split(" ")]
                    if i.attributes.get("rake_info") else None,
                    "coords":
                    coords,
                    "holes":
                    list()
                })

    print(res)
    return res
Exemplo n.º 12
0
def run():
    if not ns.filename:
        print("No Filename supplied")
        return False
    elif not ns.to:
        ns.to = 'mat'
    try:
        f = open(ns.filename, 'r')
    except:
        print("Illegal Filename")
        return False
    res = dict()
    s = svg.parse(ns.filename)
    # for i in s.items:
    #     print(i)
    #     print(i.items)
    #     if hasattr(i, "style"): print(i.style)
    res["elements"] = list()
    sres = "<svg><path d=\"M 0,0 "
    for i in s.flatten():
        if hasattr(i, "segments"):
            stroke = False
            startpoint = False
            coords = i.segments(precision=4)
            if isinstance(coords[0], list):
                for l in coords:
                    for p in l:
                        sres += "L {0} {1}".format(p[0], p[1])
            else:
                for p in coords:
                    sres += "L {0} {1}".format(p[0], p[1])
    sres += "\"/></svg>"
    # print (sres)
    return



    #         if(i.get_style("stroke-width") and i.get_style("stroke-width").val > 0 and i.get_style("stroke")):
    #             if i.get_style("stroke").val not in ["none", "#ffffff", "#fff", "#ff0000", "#00ff00"]:
    #                 stroke = True;
    #                 stroke_width = i.get_style("stroke-width").val
    #             if i.get_style("stroke").val == "#00ff00":
    #                 startpoint = true

    #         res["elements"].append({
    #             "closed": i.closed,
    #             "filled": i.get_style("fill") is not None if i.get_style("fill") else False,
    #             "stroke": stroke,
    #             "startpoint": startpoint,
    #             "manually_modified": "manually_modified" in i.attributes,
    #             "stroke_width": stroke,
    #             "rake_states": [j for j in i.attributes.get("rake_info").split(" ")] if i.attributes.get("rake_info") else None,
    #             "coords": i.segments(precision=4)[0],
    #             "holes" : None
    #             })

    # print(res)
    return
    poly = list()

    if ns.filename.endswith("dat"):
        firstline = False
        for line in f:
            if " " in line:
                (x, y) = line.rstrip("\n").split(" ")
                poly.append([x, y])
            else:
                if firstline:
                    break
                firstline = True

    elif ns.filename.endswith("svg"):
        svg_element_list = list()
        xml = f.read()
        f.close()
        soup = BeautifulSoup(xml)
        base = dict()
        base['w'] = soup.svg.width
        base['h'] = soup.svg.height

        path = soup.find_all("path")

        parse_file(ns.filename)
        # print(polys)
    if ns.to == "mat":
        text = "poly = ["
        for p2 in poly:
            text += "%s, %s;\n" % (p2[0], p2[1])
        text += "];"
        name = ns.filename.split(".")[0]
        name += ".m"
        fw = open(name, 'w')
        fw.write(text)

    if ns.to == "dat":
        text = ""
        for idx, poly in enumerate(polys):
            if(idx == 1):
                text += "%s\n" % (len(polys) - 1)
            text += "%s\n" % len(poly)
            for p2 in poly:
                text += "%s %s\n" % (p2[0], p2[1])
        text = text[:-1]
        # print(text)
        name = ns.filename.split(".")[0]
        name += ".dat"
        fw = open(name, 'w')
        fw.write(text)
Exemplo n.º 13
0
def new_parse_file(filename):
    try:
        f = open(filename, 'r')
    except:
        print("Illegal Filename")
        return False
    res = dict()
    s = svg.parse(filename)
    # for i in s.items:
    #     print(i)
    #     print(i.items)
    #     if hasattr(i, "style"): print(i.style)
    a,b = s.bbox()


    width, height = (a+b).coord()

    base = dict()
    base['width'] = float(width)
    base['height'] = float(height)
    base["rake_sizes"] = s.root.get("rake_sizes")
    if(s.root.get("scale_to_disp")):
        base['scale_for_disp'] = float(s.root.get("scale_for_disp"))
    else:
        base['scale_for_disp'] = None
    res = dict()
    res['svg_base'] = base
    res["elements"] = list()

    for i in s.flatten():
        if hasattr(i, "segments"):
            stroke = False
            startpoint = False
            stroke_width = 0
            if(i.get_style("stroke-width") and i.get_style("stroke-width").val > 0 and i.get_style("stroke")):
                if i.get_style("stroke").val not in ["none", "#ffffff", "#fff", "#ff0000", "#00ff00"]:
                    stroke = True;
                    stroke_width = i.get_style("stroke-width").val
                if i.get_style("stroke").val == "#00ff00":
                    startpoint = True
            coords = i.segments(precision=100)
            print("coords0", isinstance(coords[0], list), coords[0])
            if isinstance(coords[0], list):
                print(i.get_style("fill"))
                print("First elem list!")
                if i.closed:
                    j = 0
                    holes = list()
                    for l_coords in coords:
                        if j == 0:
                            lc = remove_adjacent(l_coords, True)
                            if signed_area(lc) > 0:
                                lc.reverse()
                        else:
                            hc = l_coords
                            # if signed_area(hc) < 0:
                            hc.reverse()
                            hc = remove_adjacent(hc, True)
                            holes.append(hc)
                        j = j + 1
                    res["elements"].append({
                        "closed": i.closed,
                        "filled": i.get_style("fill").val not in ["none", "#fff", "#ffffff", None],
                        "stroke": stroke,
                        "startpoint": startpoint,
                        "manually_modified": "manually_modified" in i.attributes,
                        "stroke_width": stroke_width,
                        "rake_states": [j for j in i.attributes.get("rake_info").split(" ")] if i.attributes.get("rake_info") else None,
                        "coords": lc,
                        "holes" : holes
                        })
                else:
                    for l_coords in coords:
                        if i.closed and signed_area(l_coords) > 0: 
                            print ("signed area  > 0")
                            l_coords.reverse()
                            # elements are holes!
                        print("LCOORDS: ", l_coords)
                        res["elements"].append({
                            "closed": i.closed,
                            "filled":  i.get_style("fill").val not in ["none", "#fff", "#ffffff", None],
                            "stroke": stroke,
                            "startpoint": startpoint,
                            "manually_modified": "manually_modified" in i.attributes,
                            "stroke_width": stroke_width,
                            "rake_states": [j for j in i.attributes.get("rake_info").split(" ")] if i.attributes.get("rake_info") else None,
                            "coords": l_coords,
                            "holes" : list()
                            })
            else:
                if i.closed and signed_area(coords) > 0: 
                    print ("signed area  > 0")
                    coords.reverse()

                res["elements"].append({
                    "closed": i.closed,
                    "filled": i.get_style("fill").val not in ["none", "#fff", "#ffffff", None],
                    "stroke": stroke,
                    "startpoint": startpoint,
                    "manually_modified": "manually_modified" in i.attributes,
                    "stroke_width": stroke_width,
                    "rake_states": [j for j in i.attributes.get("rake_info").split(" ")] if i.attributes.get("rake_info") else None,
                    "coords": coords,
                    "holes" : list()
                    })

    print(res)
    return res
Exemplo n.º 14
0
Arquivo: parse.py Projeto: vitchyr/svg
# Parse all W3C SVG testsuite files
# use it with
## python parse.py | grep ^"No handler" | sort | uniq -c | sort -n
# to get all unhandled elements sorted by occurence.

import os
import sys
sys.path.append('..')  #FIXME
import svg

path = 'W3C_SVG_11_TestSuite/svg/'

for f in os.listdir(path):
    if os.path.splitext(f)[1] == '.svg':
        svg.parse(path + f)
Exemplo n.º 15
0
# Parse all W3C SVG testsuite files
# use it with 
## python parse.py | grep ^"No handler" | sort | uniq -c | sort -n
# to get all unhandled elements sorted by occurence.

import os
import sys
sys.path.append('..') #FIXME
import svg

path = 'W3C_SVG_11_TestSuite/svg/'

for f in os.listdir(path):
    if os.path.splitext(f)[1] == '.svg':
        svg.parse(path + f)

Exemplo n.º 16
0
            low, high = sorted((room1.id, room2.id))
            key = "%s-%s" % (low, high)
            if key not in overlaps:
                overlaps[key] = ((low, high), make_rect(overlap))
    return overlaps


def make_rect(((left, top), (right, bottom))):
    return {"x": left, "y": top, "width": right - left, "height": bottom - top}


if __name__ == "__main__":

    import sys
    svg_file = sys.argv[1]
    s = svg.parse(svg_file)

    rooms = s.items[0].items[0].items[0].items
    doors = s.items[0].items[0].items[2].items

    connections = find_door_connections(doors, rooms)
    print >>sys.stderr, "Doors:", len(doors)
    print >>sys.stderr, "Connected doors:", len(connections)

    overlaps = find_room_connections(rooms)
    print >>sys.stderr, "Overlapping rooms:", len(overlaps)

    data = {}
    data["rooms"] = {r.id: {} for r in rooms}
    data["connections"] = {c: {"door": True, "locked": False,
                               "open": False, "rooms": r, "rect": b}
Exemplo n.º 17
0
def run():
    if not ns.filename:
        print("No Filename supplied")
        return False
    elif not ns.to:
        ns.to = 'mat'
    try:
        f = open(ns.filename, 'r')
    except:
        print("Illegal Filename")
        return False
    res = dict()
    s = svg.parse(ns.filename)
    # for i in s.items:
    #     print(i)
    #     print(i.items)
    #     if hasattr(i, "style"): print(i.style)
    res["elements"] = list()
    sres = "<svg><path d=\"M 0,0 "
    for i in s.flatten():
        if hasattr(i, "segments"):
            stroke = False
            startpoint = False
            coords = i.segments(precision=4)
            if isinstance(coords[0], list):
                for l in coords:
                    for p in l:
                        sres += "L {0} {1}".format(p[0], p[1])
            else:
                for p in coords:
                    sres += "L {0} {1}".format(p[0], p[1])
    sres += "\"/></svg>"
    # print (sres)
    return

    #         if(i.get_style("stroke-width") and i.get_style("stroke-width").val > 0 and i.get_style("stroke")):
    #             if i.get_style("stroke").val not in ["none", "#ffffff", "#fff", "#ff0000", "#00ff00"]:
    #                 stroke = True;
    #                 stroke_width = i.get_style("stroke-width").val
    #             if i.get_style("stroke").val == "#00ff00":
    #                 startpoint = true

    #         res["elements"].append({
    #             "closed": i.closed,
    #             "filled": i.get_style("fill") is not None if i.get_style("fill") else False,
    #             "stroke": stroke,
    #             "startpoint": startpoint,
    #             "manually_modified": "manually_modified" in i.attributes,
    #             "stroke_width": stroke,
    #             "rake_states": [j for j in i.attributes.get("rake_info").split(" ")] if i.attributes.get("rake_info") else None,
    #             "coords": i.segments(precision=4)[0],
    #             "holes" : None
    #             })

    # print(res)
    return
    poly = list()

    if ns.filename.endswith("dat"):
        firstline = False
        for line in f:
            if " " in line:
                (x, y) = line.rstrip("\n").split(" ")
                poly.append([x, y])
            else:
                if firstline:
                    break
                firstline = True

    elif ns.filename.endswith("svg"):
        svg_element_list = list()
        xml = f.read()
        f.close()
        soup = BeautifulSoup(xml)
        base = dict()
        base['w'] = soup.svg.width
        base['h'] = soup.svg.height

        path = soup.find_all("path")

        parse_file(ns.filename)
        # print(polys)
    if ns.to == "mat":
        text = "poly = ["
        for p2 in poly:
            text += "%s, %s;\n" % (p2[0], p2[1])
        text += "];"
        name = ns.filename.split(".")[0]
        name += ".m"
        fw = open(name, 'w')
        fw.write(text)

    if ns.to == "dat":
        text = ""
        for idx, poly in enumerate(polys):
            if (idx == 1):
                text += "%s\n" % (len(polys) - 1)
            text += "%s\n" % len(poly)
            for p2 in poly:
                text += "%s %s\n" % (p2[0], p2[1])
        text = text[:-1]
        # print(text)
        name = ns.filename.split(".")[0]
        name += ".dat"
        fw = open(name, 'w')
        fw.write(text)
Exemplo n.º 18
0
            cr.rectangle(x1, y1, width, height)


def draw_with_segments(cr, drawing):
    for d in drawing:
        if hasattr(d, 'segments'):
            for l in d.segments(1):
                x,y = l[0].coord()
                cr.move_to(x,y)
                for pt in l[1:]:
                    x,y = pt.coord()
                    cr.line_to(x,y)
        else:
            print("Unsupported SVG element")

f = svg.parse(sys.argv[1])

a,b = f.bbox()

width, height = (a+b).coord()
surface = cairo.SVGSurface("test.svg", width, height)
cr = cairo.Context(surface)

cr.set_source_rgb(0,0,0)
cr.set_line_width(1)

#draw_with_cairo(cr, f.flatten())
draw_with_segments(cr, f.flatten())

cr.stroke()
Exemplo n.º 19
0

def draw_with_segments(cr, drawing):
    for d in drawing:
        if hasattr(d, 'segments'):
            for l in d.segments(1):
                x, y = l[0].coord()
                cr.move_to(x, y)
                for pt in l[1:]:
                    x, y = pt.coord()
                    cr.line_to(x, y)
        else:
            print("Unsupported SVG element")


f = svg.parse(sys.argv[1])

a, b = f.bbox()

width, height = (a + b).coord()
surface = cairo.SVGSurface("test.svg", width, height)
cr = cairo.Context(surface)

cr.set_source_rgb(0, 0, 0)
cr.set_line_width(1)

#draw_with_cairo(cr, f.flatten())
draw_with_segments(cr, f.flatten())

cr.stroke()