1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
|
""" Small hand-written recursive descent parser for SVG <path> data.
In [1]: from svg_regex import svg_parser
In [3]: svg_parser.parse('M 10,20 30,40V50 60 70')
Out[3]: [('M', [(10.0, 20.0), (30.0, 40.0)]), ('V', [50.0, 60.0, 70.0])]
In [4]: svg_parser.parse('M 0.6051.5') # An edge case
Out[4]: [('M', [(0.60509999999999997, 0.5)])]
In [5]: svg_parser.parse('M 100-200') # Another edge case
Out[5]: [('M', [(100.0, -200.0)])]
"""
import re
# Sentinel.
class _EOF(object):
def __repr__(self):
return 'EOF'
EOF = _EOF()
lexicon = [
('float', r'[-\+]?(?:(?:[0-9]*\.[0-9]+)|(?:[0-9]+\.?))(?:[Ee][-\+]?[0-9]+)?'),
('int', r'[-\+]?[0-9]+'),
('command', r'[AaCcHhLlMmQqSsTtVvZz]'),
]
class Lexer(object):
""" Break SVG path data into tokens.
The SVG spec requires that tokens are greedy. This lexer relies on Python's
regexes defaulting to greediness.
This style of implementation was inspired by this article:
http://www.gooli.org/blog/a-simple-lexer-in-python/
"""
def __init__(self, lexicon):
self.lexicon = lexicon
parts = []
for name, regex in lexicon:
parts.append('(?P<%s>%s)' % (name, regex))
self.regex_string = '|'.join(parts)
self.regex = re.compile(self.regex_string)
def lex(self, text):
""" Yield (token_type, str_data) tokens.
The last token will be (EOF, None) where EOF is the singleton object
defined in this module.
"""
for match in self.regex.finditer(text):
for name, _ in self.lexicon:
m = match.group(name)
if m is not None:
yield (name, m)
break
yield (EOF, None)
svg_lexer = Lexer(lexicon)
class SVGPathParser(object):
""" Parse SVG <path> data into a list of commands.
Each distinct command will take the form of a tuple (command, data). The
`command` is just the character string that starts the command group in the
<path> data, so 'M' for absolute moveto, 'm' for relative moveto, 'Z' for
closepath, etc. The kind of data it carries with it depends on the command.
For 'Z' (closepath), it's just None. The others are lists of individual
argument groups. Multiple elements in these lists usually mean to repeat the
command. The notable exception is 'M' (moveto) where only the first element
is truly a moveto. The remainder are implicit linetos.
See the SVG documentation for the interpretation of the individual elements
for each command.
The main method is `parse(text)`. It can only consume actual strings, not
filelike objects or iterators.
"""
def __init__(self, lexer=svg_lexer):
self.lexer = lexer
self.command_dispatch = {
'Z': self.rule_closepath,
'z': self.rule_closepath,
'M': self.rule_moveto_or_lineto,
'm': self.rule_moveto_or_lineto,
'L': self.rule_moveto_or_lineto,
'l': self.rule_moveto_or_lineto,
'H': self.rule_orthogonal_lineto,
'h': self.rule_orthogonal_lineto,
'V': self.rule_orthogonal_lineto,
'v': self.rule_orthogonal_lineto,
'C': self.rule_curveto3,
'c': self.rule_curveto3,
'S': self.rule_curveto2,
's': self.rule_curveto2,
'Q': self.rule_curveto2,
'q': self.rule_curveto2,
'T': self.rule_curveto1,
't': self.rule_curveto1,
'A': self.rule_elliptical_arc,
'a': self.rule_elliptical_arc,
}
self.number_tokens = set(['int', 'float'])
def parse(self, text):
""" Parse a string of SVG <path> data.
"""
next = self.lexer.lex(text).next
token = next()
return self.rule_svg_path(next, token)
def rule_svg_path(self, next, token):
commands = []
while token[0] is not EOF:
if token[0] != 'command':
raise SyntaxError("expecting a command; got %r" % (token,))
rule = self.command_dispatch[token[1]]
command_group, token = rule(next, token)
commands.append(command_group)
return commands
def rule_closepath(self, next, token):
command = token[1]
token = next()
return (command, None), token
def rule_moveto_or_lineto(self, next, token):
command = token[1]
token = next()
coordinates = []
while token[0] in self.number_tokens:
pair, token = self.rule_coordinate_pair(next, token)
coordinates.append(pair)
return (command, coordinates), token
def rule_orthogonal_lineto(self, next, token):
command = token[1]
token = next()
coordinates = []
while token[0] in self.number_tokens:
coord, token = self.rule_coordinate(next, token)
coordinates.append(coord)
return (command, coordinates), token
def rule_curveto3(self, next, token):
command = token[1]
token = next()
coordinates = []
while token[0] in self.number_tokens:
pair1, token = self.rule_coordinate_pair(next, token)
pair2, token = self.rule_coordinate_pair(next, token)
pair3, token = self.rule_coordinate_pair(next, token)
coordinates.append((pair1, pair2, pair3))
return (command, coordinates), token
def rule_curveto2(self, next, token):
command = token[1]
token = next()
coordinates = []
while token[0] in self.number_tokens:
pair1, token = self.rule_coordinate_pair(next, token)
pair2, token = self.rule_coordinate_pair(next, token)
coordinates.append((pair1, pair2))
return (command, coordinates), token
def rule_curveto1(self, next, token):
command = token[1]
token = next()
coordinates = []
while token[0] in self.number_tokens:
pair1, token = self.rule_coordinate_pair(next, token)
coordinates.append(pair1)
return (command, coordinates), token
def rule_elliptical_arc(self, next, token):
command = token[1]
token = next()
arguments = []
while token[0] in self.number_tokens:
rx = float(token[1])
if rx < 0.0:
raise SyntaxError("expecting a nonnegative number; got %r" % (token,))
token = next()
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
ry = float(token[1])
if ry < 0.0:
raise SyntaxError("expecting a nonnegative number; got %r" % (token,))
token = next()
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
axis_rotation = float(token[1])
token = next()
if token[1] not in ('0', '1'):
raise SyntaxError("expecting a boolean flag; got %r" % (token,))
large_arc_flag = bool(int(token[1]))
token = next()
if token[1] not in ('0', '1'):
raise SyntaxError("expecting a boolean flag; got %r" % (token,))
sweep_flag = bool(int(token[1]))
token = next()
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
x = float(token[1])
token = next()
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
y = float(token[1])
token = next()
arguments.append(((rx,ry), axis_rotation, large_arc_flag, sweep_flag, (x,y)))
return (command, arguments), token
def rule_coordinate(self, next, token):
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
x = float(token[1])
token = next()
return x, token
def rule_coordinate_pair(self, next, token):
# Inline these since this rule is so common.
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
x = float(token[1])
token = next()
if token[0] not in self.number_tokens:
raise SyntaxError("expecting a number; got %r" % (token,))
y = float(token[1])
token = next()
return (x,y), token
svg_parser = SVGPathParser()
|