Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import subprocess
- import itertools
- from HTMLParser import HTMLParser
- DPs = 3
- StateNames = {
- 'AL': 'Alabama',
- 'AK': 'Alaska',
- 'AZ': 'Arizona',
- 'AR': 'Arkansas',
- 'CA': 'California',
- 'CO': 'Colorado',
- 'CT': 'Connecticut',
- 'DE': 'Delaware',
- 'FL': 'Florida',
- 'GA': 'Georgia',
- 'HI': 'Hawaii',
- 'ID': 'Idaho',
- 'IL': 'Illinois',
- 'IN': 'Indiana',
- 'IA': 'Iowa',
- 'KS': 'Kansas',
- 'KY': 'Kentucky',
- 'LA': 'Louisiana',
- 'MA': 'Massachusetts',
- 'MD': 'Maryland',
- 'ME': 'Maine',
- 'MI': 'Michigan',
- 'MN': 'Minnesota',
- 'MO': 'Missouri',
- 'MS': 'Mississippi',
- 'MT': 'Montana',
- 'NE': 'Nebraska',
- 'NV': 'Nevada',
- 'NH': 'New Hampshire',
- 'NJ': 'New Jersey',
- 'NM': 'New Mexico',
- 'NY': 'New York',
- 'NC': 'North Carolina',
- 'ND': 'North Dakota',
- 'OH': 'Ohio',
- 'OK': 'Oklahoma',
- 'OR': 'Oregon',
- 'PA': 'Pennsylvania',
- 'RI': 'Rhode Island',
- 'SC': 'South Carolina',
- 'SD': 'South Dakota',
- 'TN': 'Tennessee',
- 'TX': 'Texas',
- 'UT': 'Utah',
- 'VT': 'Vermont',
- 'VA': 'Virginia',
- 'WA': 'Washington',
- 'WV': 'West Virginia',
- 'WI': 'Wisconsin',
- 'WY': 'Wyoming',
- 'PR': 'Puerto Rico',
- 'VI': 'Virgin Islands',
- 'GU': 'Guam',
- 'AS': 'American Samoa',
- 'MP': 'Morthern Mariana Islands',
- 'DC': 'Washington D.C.'
- }
- Centres = {
- 'AL': (648, 415),
- 'AK': (112, 542),
- 'AZ': (203, 364),
- 'AR': (545, 369),
- 'CA': (71, 274),
- 'CO': (320, 272),
- 'CT': (858, 178),
- 'DE': (826, 243),
- 'FL': (722, 502),
- 'GA': (710, 405),
- 'HI': (285, 552),
- 'ID': (185, 119),
- 'IL': (590, 258),
- 'IN': (638, 253),
- 'IA': (518, 213),
- 'KS': (440, 293),
- 'KY': (658, 305),
- 'LA': (563, 458),
- 'MA': (874, 162),
- 'MD': (798, 252),
- 'ME': (888, 86),
- 'MI': (635, 142),
- 'MN': (521, 114),
- 'MO': (538, 297),
- 'MS': (595, 416),
- 'MT': (270, 87),
- 'NE': (420, 225),
- 'NV': (140, 241),
- 'NH': (865, 123),
- 'NJ': (832, 216),
- 'NM': (298, 379),
- 'NY': (812, 160),
- 'NC': (768, 332),
- 'ND': (416, 96),
- 'OH': (701, 234),
- 'OK': (434, 359),
- 'OR': (95, 120),
- 'PA': (780, 211),
- 'RI': (877, 171),
- 'SC': (751, 371),
- 'SD': (414, 160),
- 'TN': (658, 343),
- 'TX': (405, 452),
- 'UT': (218, 250),
- 'VT': (848, 126),
- 'VA': (767, 290),
- 'WA': (115, 47),
- 'WV': (749, 266),
- 'WI': (575, 155),
- 'WY': (295, 183),
- 'DC': (801.33209, 251.79613),
- 'PR': (596, 537),
- 'VI': (657, 537),
- 'GU': (579, 575),
- 'AS': (615, 575),
- 'MP': (657, 575)
- }
- Bumps = {
- 'HI': (-8, 0),
- 'VI': (0, -1)
- }
- NewOrigins = {
- 'AK': (0, 425),
- 'HI': (211, 492),
- 'PR': (560, 516),
- 'VI': (633, 516),
- 'GU': (560, 557),
- 'AS': (597, 557),
- 'MP': (633, 557)
- }
- def MaxDP(x, n):
- '''Return as a string, x at a maximum of n decimal places.'''
- s = '%.*f' % (n, x)
- if '.' in s:
- while s[-1:] == '0':
- s = s[:-1]
- if s[-1:] == '.':
- s = s[:-1]
- return s
- def VSum(*VectorArgs):
- if len(VectorArgs) == 1:
- Vectors = VectorArgs[0]
- else:
- Vectors = VectorArgs
- Result = tuple(Vectors[0])
- for i in range(1, len(Vectors)):
- Result = tuple(a + b for a, b in zip(Result, Vectors[i]))
- return Result
- def VDiff(A, B):
- return tuple(x - y for x, y in zip(A, B))
- def ShiftedPD(PathData, Transform, NumDPs=2):
- CmdSet = 'MLHVQTCSAZ'
- x, y = Transform
- ArgFormats = {
- 'M': 'x,y',
- 'L': 'x,y',
- 'H': 'x',
- 'V': 'y',
- 'Q': 'x,y x,y',
- 'T': 'x,y',
- 'C': 'x,y x,y x,y',
- 'S': 'x,y x,y',
- 'A': '0,0 0,0,0 x,y',
- 'Z': '0'
- }
- Result = ''
- CmdStr = ''
- CmdStrs = []
- for Ch in PathData:
- if Ch.upper() in CmdSet:
- CmdStr = CmdStr.rstrip()
- if CmdStr != '':
- CmdStrs.append(CmdStr)
- CmdStr = ''
- CmdStr += Ch
- CmdStr = CmdStr.rstrip()
- if CmdStr != '':
- CmdStrs.append(CmdStr)
- NewCmdStrs = []
- HaveRefX = False
- HaveRefY = False
- for CmdStr in CmdStrs:
- Cmd = CmdStr[0]
- CmdIsAbs = Cmd == Cmd.upper() and Cmd not in 'Zz'
- ForceAbsCmd = False
- ArgStrs = list(itertools.chain.from_iterable(
- [S.split() for S in CmdStr[1:].split(',')]))
- Args = [float(S) for S in ArgStrs]
- ArgFmt = ArgFormats[Cmd.upper()]
- ArgStrs = []
- ArgFmtIx = 0
- for Arg in Args:
- if ArgFmtIx >= len(ArgFmt):
- ArgStrs += ' ' + Cmd + ' '
- ArgFmtIx = 0
- while ArgFmt[ArgFmtIx] not in '0xy':
- ArgStrs += ArgFmt[ArgFmtIx]
- ArgFmtIx += 1
- Ch = ArgFmt[ArgFmtIx]
- ArgFmtIx += 1
- Delta = 0
- if Ch == 'x':
- if CmdIsAbs or not HaveRefX:
- Delta = x
- ForceAbsCmd = ForceAbsCmd or not HaveRefX
- HaveRefX = True
- elif Ch == 'y':
- if CmdIsAbs or not HaveRefY:
- Delta = y
- ForceAbsCmd = ForceAbsCmd or not HaveRefY
- HaveRefY = True
- ArgStrs.append(MaxDP(Arg + Delta, NumDPs))
- NewCmdStr = Cmd.upper() if ForceAbsCmd else Cmd
- if len(ArgStrs) > 0 and Cmd not in 'Zz':
- NewCmdStr += ' ' + ''.join(ArgStrs)
- NewCmdStrs.append(NewCmdStr)
- Result = ' '.join(NewCmdStrs)
- return Result
- def WrapPathData(PathData, FirstIndentStr, IndentStr, Terminator, MaxColumns):
- Result = []
- CmdSet = 'MLHVQTCSAZ'
- CmdStr = ''
- CmdStrs = []
- for Ch in PathData:
- if Ch.upper() in CmdSet:
- CmdStr = CmdStr.rstrip()
- if CmdStr != '':
- CmdStrs.append(CmdStr)
- CmdStr = ''
- CmdStr += Ch
- CmdStr = CmdStr.rstrip()
- if CmdStr != '':
- CmdStrs.append(CmdStr)
- Line = FirstIndentStr
- LastCmd = '?'
- Sep = ''
- for Ix, CmdStr in enumerate(CmdStrs):
- IsLast = Ix + 1 == len(CmdStrs)
- NoMoreRoom = len(Line) + len(Sep) + len(CmdStr) > MaxColumns
- DoWrap = NoMoreRoom or LastCmd in 'Zz'
- if DoWrap:
- Result += [Line]
- Line = IndentStr + CmdStr
- else:
- Line += Sep + CmdStr
- Sep = ' '
- LastCmd = CmdStr[0]
- if len(Line) + len(Terminator) > MaxColumns:
- Result += [Line]
- Line = IndentStr
- Result += [Line + Terminator]
- return Result
- psIdle = 0
- psDefs = 1
- psClipPath = 2
- psCPPath = 3
- class MyParser(HTMLParser):
- def __init__(self):
- HTMLParser.__init__(self)
- self.State = psIdle
- self.CPID = None
- self.CPPaths = None
- self.ClipPaths = {}
- self.NewClipPaths = {}
- self.ClipPathNames = []
- self.Shapes = {}
- self.ShapeNames = []
- self.ShapeNamesByClipPathName = {}
- def GetAttr(self, Attributes, AttrName):
- Result = None
- for (Name, Value) in Attributes:
- if Name == AttrName:
- Result = Value
- break
- return Result
- def handle_starttag(self, tag, attrs):
- #print 'Start', tag
- #print ' ' + repr(attrs)
- if self.State == psDefs:
- if tag == 'clippath':
- self.State = psClipPath
- self.CPID = self.GetAttr(attrs, 'id')
- self.CPPaths = []
- elif self.State == psClipPath:
- if tag == 'path':
- PathID = self.GetAttr(attrs, 'id')
- PathData = self.GetAttr(attrs, 'd')
- self.CPPaths.append((PathID, PathData))
- self.State = psCPPath
- elif self.State == psCPPath:
- pass
- else:
- if tag == 'defs':
- self.State = psDefs
- if tag == 'use':
- ID = self.GetAttr(attrs, 'id')
- if ID is not None and len(ID) == 2:
- XLink = self.GetAttr(attrs, 'xlink:href')
- CPID = self.GetAttr(attrs, 'clip-path')[len('url(#'):-1]
- TranslateStr = self.GetAttr(attrs, 'transform')[len('translate('):-1]
- Transform = tuple([float(S) for S in
- (TranslateStr.split(',') + ['0', '0'])[:2]])
- if ID == 'DC':
- Transform = (0, 0)
- if CPID in self.ClipPaths:
- Prec = 5 if ID in ['PR', 'VI', 'GU', 'AS', 'MP'] else 3
- if ID in Bumps:
- Transform = VSum(Transform, Bumps[ID])
- if ID in NewOrigins:
- Transform = VDiff(Transform, NewOrigins[ID])
- NewCPPaths = []
- for (PathID, PathData) in self.ClipPaths[CPID]:
- NewPathData = ShiftedPD(PathData, Transform, Prec)
- NewCPPaths.append((PathID, NewPathData))
- self.NewClipPaths[CPID] = NewCPPaths
- self.Shapes[ID] = (CPID, XLink)
- self.ShapeNames.append(ID)
- self.ShapeNamesByClipPathName[CPID] = ID
- def handle_endtag(self, tag):
- #print 'End', tag
- if self.State == psDefs:
- if tag == 'defs':
- self.State = psIdle
- elif self.State == psClipPath:
- if tag == 'clippath':
- self.ClipPaths[self.CPID] = self.CPPaths
- self.ClipPathNames.append(self.CPID)
- self.CPID = None
- self.CPPaths = None
- self.State = psDefs
- elif self.State == psCPPath:
- if tag == 'path':
- self.State = psClipPath
- else:
- pass
- def handle_data(self, data):
- pass
- def Main():
- #URL = 'http://www.pidjin.net/2006/03/06/such-a-perfect-day/'
- URL = 'http://www.realhamster.com/'
- f = open('USA-SSM.svg', 'r')
- try:
- Page = f.readlines()
- H = MyParser()
- for Line in Page:
- H.feed(Line)
- finally:
- f.close()
- Lines = []
- for CPName in H.ClipPathNames:
- Name = H.ShapeNamesByClipPathName[CPName]
- Lines += [' <!-- ' + StateNames[Name] + ' -->']
- Lines += ['']
- Lines += [' <clipPath id="' + CPName + '">']
- for (PathID, PathData) in H.NewClipPaths[CPName]:
- Lines += WrapPathData(
- PathData,
- ' <path id="' + PathID + '" d="',
- ' ' * 8,
- '"/>',
- 80
- )
- Lines += [' </clipPath>']
- Lines += ['']
- Lines += ['']
- for Name in H.ShapeNames:
- (CPID, XLink) = H.Shapes[Name]
- Centre = Centres[Name]
- if Name in NewOrigins:
- Origin = NewOrigins[Name]
- Centre = VDiff(Centre, Origin)
- OrgStr = MaxDP(Origin[0], DPs) + ',' + MaxDP(Origin[1], DPs)
- GXformStr = ' transform="translate(' + OrgStr + ')"'
- else:
- GXformStr = ''
- CentreStr = MaxDP(Centre[0], DPs) + ',' + MaxDP(Centre[1], DPs)
- PatXformStr = 'transform="translate(' + CentreStr + ')"'
- Lines += [' <!-- ' + StateNames[Name] + ' -->']
- Lines += [' <g clip-path="url(#' + CPID + ')"' + GXformStr + '>']
- Lines += [' <use xlink:href="' + XLink + '" ' + PatXformStr + '/>']
- Lines += [' </g>']
- print '\n'.join(Lines)
- if __name__ == '__main__':
- Main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement