示例#1
0
文件: util.py 项目: ig2gi/philo_graph
 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
示例#2
0
文件: svg2mod.py 项目: mtl/svg2mod
    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 )
示例#3
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
示例#4
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)
示例#5
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
示例#6
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)

            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}
示例#8
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()