source: subversion/applications/rendering/parking/mapnik/generate_parking_layer_xml.py @ 26359

Last change on this file since 26359 was 26359, checked in by kdrangmeister, 9 years ago

change deployment

  • Property svn:mime-type set to text/plain
File size: 16.1 KB
Line 
1# -*- coding: utf-8 -*-
2# by kay
3
4import sys,os,subprocess
5from optparse import OptionParser
6#from xml.dom.minidom import parse, parseString
7import pxdom
8
9#import colorsys
10
11condition_colors = {
12    'free': '7fff00',
13    'disc': '50a100',
14    'cust': 'b68529',
15    'resi': '785534',
16    'priv': '3f2920',
17    'fee':  '67a1eb',
18    'unkn': 'bc73e2'
19    }
20
21forbidden_colors = {
22    'nopa': 'f8b81f',
23    'nost': 'f85b1f',
24    'fire': 'f81f1f'
25    }
26
27
28"""
29def dom_convert_to_grey(document):
30    els = document.getElementsByTagName("CssParameter")
31    #print "els=",els
32    for el in els:
33        at = el.getAttribute("name")
34        if at=="stroke" or at=="fill":
35            col=el.firstChild.nodeValue
36            bw=rgb_to_css(color_to_bw(parse_color(col)))
37            print "converted {typ} from {a} to {bw}." .format(typ=at,a=col,bw=bw)
38            el.firstChild.nodeValue=bw
39
40    #<Map bgcolor="---" srs="+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" minimum_version="0.7.1">
41    els = document.getElementsByTagName("Map")
42    for el in els:
43        col = el.getAttribute("bgcolor")
44        assert(col!='')
45        assert(col!=None)
46        bw=rgb_to_css(color_to_bw(parse_color(col)))
47        print "converted {typ} from {a} to {bw}." .format(typ='bgcolor',a=col,bw=bw)
48        el.setAttribute("bgcolor",bw)
49
50    #<TextSymbolizer ... fill="#6699cc"/>
51    els = document.getElementsByTagName("TextSymbolizer")
52    for el in els:
53        col = el.getAttribute("fill")
54        assert(col!='')
55        assert(col!=None)
56        bw=rgb_to_css(color_to_bw(parse_color(col)))
57        print "converted {typ} from {a} to {bw}." .format(typ='TS-fill',a=col,bw=bw)
58        el.setAttribute("fill",bw)
59        #<TextSymbolizer halo_fill="#fed7a5"/> (optional)
60        col = el.getAttribute("halo_fill")
61        assert(col!=None)
62        if col!='':
63            bw=rgb_to_css(color_to_bw(parse_color(col)))
64            print "converted {typ} from {a} to {bw}." .format(typ='TS-halo_fill',a=col,bw=bw)
65            el.setAttribute("halo_fill",bw)
66"""
67
68def dom_strip_style_and_layer(document,stylename,layername):
69    removeElements=[]
70    # remove <Style name="points"> and <Layer name="amenity-points">
71    els = document.getElementsByTagName("Style")
72    for el in els:
73        if el.getAttribute("name")==stylename:
74            removeElements.append(el)
75    els = document.getElementsByTagName("Layer")
76    for el in els:
77        if el.getAttribute("name")==layername:
78            removeElements.append(el)
79    print "removing the following elements:"
80    print removeElements
81    for el in removeElements:
82        parent = el.parentNode
83        parent.removeChild(el)
84
85def dom_strip_icons(document):
86    dom_strip_style_and_layer(document,"points","amenity-points")
87    dom_strip_style_and_layer(document,"power_line","power_line")
88    dom_strip_style_and_layer(document,"power_minorline","power_minorline")
89    dom_strip_style_and_layer(document,"power_towers","power_towers")
90    dom_strip_style_and_layer(document,"power_poles","power_poles")
91
92def transmogrify_file(sf,dfgrey,dfnoicons):
93    dom= pxdom.getDOMImplementation('')
94    parser= dom.createLSParser(dom.MODE_SYNCHRONOUS, None)
95    parser.domConfig.setParameter('entities', 0) # 1 -> exception if attribute values is set
96    #parser.domConfig.setParameter('disallow-doctype', 1)
97    parser.domConfig.setParameter('pxdom-resolve-resources', 1) # 1 -> replace &xyz; with text
98    document = parser.parseURI(sf)
99
100#    dom_convert_to_grey(document)
101   
102    output= document.implementation.createLSOutput()
103    output.systemId= dfgrey
104    output.encoding= 'utf-8'
105    serialiser= document.implementation.createLSSerializer()
106    serialiser.write(document, output)
107
108"""
109    dom_strip_icons(document)
110   
111    output= document.implementation.createLSOutput()
112    output.systemId= dfnoicons
113    output.encoding= 'utf-8'
114    serialiser= document.implementation.createLSSerializer()
115    serialiser.write(document, output)
116"""
117
118def strip_doctype(f):
119    p = subprocess.Popen(['sed','-i','2,9 d',f]) # -i means 'in place'
120    p.wait()
121
122def create_parking_icons(source_symbols_dir,dest_symbols_dir):
123    create_parking_lane_icons(source_symbols_dir,dest_symbols_dir)
124    create_parking_area_icons(source_symbols_dir,dest_symbols_dir)
125   
126def create_parking_lane_icons(source_symbols_dir,dest_symbols_dir):
127    # first create mirror images (from left to right)
128    image_files = os.listdir(source_symbols_dir)
129    image_files = [f for f in image_files if f.startswith('park-l') and f.endswith('png')]
130    for f in image_files:
131        sf = os.path.join(source_symbols_dir,f)
132        df = os.path.join(source_symbols_dir,f) # this is changed so that we write in the source dir
133        hflip_icon(sf,df.replace('-l','-r'))
134
135    # then, create the colors
136    image_files = os.listdir(source_symbols_dir)
137    image_files = [f for f in image_files if f.endswith('source.png')]
138    for f in image_files:
139        # convert ./original-mapnik/symbols/*.png -fx '0.25*r + 0.62*g + 0.13*b' ./bw-mapnik/symbols/*.png
140        sf = os.path.join(source_symbols_dir,f)
141        df = os.path.join(dest_symbols_dir,f)
142        if 'n-' in f:      # then it's a non-parking thing
143            for c in forbidden_colors.iterkeys():
144                colorize_icon(sf,df.replace('source',c),forbidden_colors.get(c))
145        else:
146            for c in condition_colors.iterkeys():
147                colorize_icon(sf,df.replace('source',c),condition_colors.get(c))
148
149def create_parking_area_icons(source_symbols_dir,dest_symbols_dir):
150    df = os.path.join(dest_symbols_dir,"parking_area_source.png")
151    stampf = os.path.join(source_symbols_dir,"parking_area_stamp.png")
152    for c in condition_colors.iterkeys():
153        p = subprocess.Popen(['convert','-size','16x16','xc:#'+condition_colors.get(c),stampf,'-compose','Darken','-composite',df.replace('source',c)])
154        p.wait()
155
156def create_parking_area_icons_delete(source_symbols_dir,dest_symbols_dir):
157    image_files = os.listdir(source_symbols_dir)
158    image_files = [f for f in image_files if f.startswith('parking_area') and f.endswith('source.png')]
159    print "all image files:", image_files
160    for f in image_files:
161        sf = os.path.join(source_symbols_dir,f)
162        df = os.path.join(dest_symbols_dir,f)
163        stampf = sf.replace('source','stamp')
164        print "stampf", stampf
165        for c in condition_colors.iterkeys():
166            colorize_icon(sf,df.replace('source',c),condition_colors.get(c))
167            stamp_icon(df.replace('source',c),df.replace('source',c),stampf)
168
169def colorize_icon(sf,df,color):
170    p = subprocess.Popen(['convert',sf,'-fill','#'+color,'-colorize','100',df])
171    p.wait()
172
173def hflip_icon(sf,df):
174    p = subprocess.Popen(['convert',sf,'-flip',df])
175    p.wait()
176
177def stamp_icon(sf,df,stampf):
178    p = subprocess.Popen(['convert',sf,stampf,'-compose','Darken','-composite',df])
179    p.wait()
180
181def add_license_files(dirname):
182    f = open(os.path.join(dirname,"CONTACT"), 'w')
183    f.write("This style is created by kayd@toolserver.org")
184    f.close
185    f = open(os.path.join(dirname,"LICENSE"), 'w')
186    f.write("This derived work is published by the author, Kay Drangmeister, under the same license as the original OSM mapnik style sheet (found here: http://svn.openstreetmap.org/applications/rendering/mapnik)")
187    f.close
188
189def main_parktrans(options):
190    style_name = options['stylename']
191    source_dir = options['sourcedir']
192    source_file = options['sourcefile']
193    #source_symbols_dir_mapnik = os.path.join(source_dir,"symbols")
194    source_symbols_dir_style = os.path.join(source_dir,"parking-symbols-src")
195    dest_dir = options['destdir']
196
197    # parktrans - transparent layer to be put on top of mapnik or bw-noicons base layer
198   
199    dest_dir_style = os.path.join(dest_dir,style_name)
200    dest_dir_style_symbols = os.path.join(dest_dir_style,"symbols")
201    dest_file_style = 'osm-{style}.xml'.format(style=style_name)
202    style_file = os.path.join(dest_dir_style,dest_file_style)
203    if not os.path.exists(dest_dir_style_symbols):
204        os.makedirs(dest_dir_style_symbols)
205
206    create_parking_icons(source_symbols_dir_style,dest_dir_style_symbols)
207    transmogrify_file(os.path.join(source_dir,source_file),style_file,"")
208    strip_doctype(style_file)
209    add_license_files(dest_dir_style)
210
211def main_parking(options):
212    style_name = options['stylename']
213    source_dir = options['sourcedir']
214    source_file = options['sourcefile']
215    source_symbols_dir_style = os.path.join(source_dir,"parking-symbols-src")
216    dest_dir = options['destdir']
217
218    # parking - bw-noicons background ans parking information on top - single layer containing all
219
220    dest_dir_style = os.path.join(dest_dir,style_name)
221    dest_dir_style_symbols = os.path.join(dest_dir_style,"symbols")
222    dest_file_style = 'osm-{style}.xml'.format(style=style_name)
223    style_file = os.path.join(dest_dir_style,dest_file_style)
224    if not os.path.exists(dest_dir_style_symbols):
225        os.makedirs(dest_dir_style_symbols)
226
227    create_parking_icons(source_symbols_dir_style,dest_dir_style_symbols)
228    transmogrify_file(os.path.join(source_dir,source_file),style_file,"")
229    strip_doctype(style_file)
230    add_license_files(dest_dir_style)
231
232def main_parking_neu(options):
233    style_name = options['stylename']
234    source_bwn_dir = options['sourcebwndir']
235    source_bwn_file = options['sourcebwnfile']
236    source_p_dir = options['sourcepdir']
237    source_p_file = options['sourcepfile']
238    source_symbols_dir_style = os.path.join(source_p_dir,"parking-symbols-src")
239    dest_dir = options['destdir']
240
241    dest_dir_style = os.path.join(dest_dir,style_name)
242    dest_dir_style_symbols = os.path.join(dest_dir_style,"symbols")
243    dest_file_style = 'osm-parking-neu.xml'
244    style_file = os.path.join(dest_dir_style,dest_file_style)
245    if not os.path.exists(dest_dir_style_symbols):
246        os.makedirs(dest_dir_style_symbols)
247
248    create_parking_icons(source_symbols_dir_style,dest_dir_style_symbols)
249    merge_bw_noicons_and_parktrans_style(os.path.join(source_bwn_dir,source_bwn_file),os.path.join(source_p_dir,source_p_file),style_file)
250    #strip_doctype(style_file)
251    add_license_files(dest_dir_style)
252
253def merge_bw_noicons_and_parktrans_style(bwnoicons_style_file,parktrans_style_file,dest_parking_style_file):
254    dom= pxdom.getDOMImplementation('')
255    parser= dom.createLSParser(dom.MODE_SYNCHRONOUS, None)
256    parser.domConfig.setParameter('entities', 0) # 1 -> exception if attribute values is set
257    #parser.domConfig.setParameter('disallow-doctype', 1)
258    parser.domConfig.setParameter('pxdom-resolve-resources', 1) # 1 -> replace &xyz; with text
259    dest_parking_style_document = parser.parseURI(bwnoicons_style_file)
260    parktrans_style_document = parser.parseURI(parktrans_style_file)
261
262#    dom_convert_to_grey(document)
263    parking_area_style = dest_parking_style_document.adoptNode(parking_dom_cut_style(parktrans_style_document,'parking-area'))
264    parking_area_layer = dest_parking_style_document.adoptNode(parking_dom_cut_layer(parktrans_style_document,'parking-area'))
265    #parking_dom_insert_things_before_layer(dest_parking_style_document,parking_area_style,'planet roads text osm low zoom')
266    #parking_dom_insert_things_before_layer(dest_parking_style_document,parking_area_layer,'planet roads text osm low zoom')
267    things=[parking_area_style,parking_area_layer]
268    parking_dom_insert_things_before_layer(dest_parking_style_document,things,'planet roads text osm low zoom')
269
270    pllno = dest_parking_style_document.adoptNode(parking_dom_cut_style(parktrans_style_document,'parkinglane-left-no'))
271    plrno = dest_parking_style_document.adoptNode(parking_dom_cut_style(parktrans_style_document,'parkinglane-right-no'))
272    pllin = dest_parking_style_document.adoptNode(parking_dom_cut_style(parktrans_style_document,'parkinglane-left-inline'))
273    plrin = dest_parking_style_document.adoptNode(parking_dom_cut_style(parktrans_style_document,'parkinglane-right-inline'))
274    plldi = dest_parking_style_document.adoptNode(parking_dom_cut_style(parktrans_style_document,'parkinglane-left-diagonal'))
275    plrdi = dest_parking_style_document.adoptNode(parking_dom_cut_style(parktrans_style_document,'parkinglane-right-diagonal'))
276    pllor = dest_parking_style_document.adoptNode(parking_dom_cut_style(parktrans_style_document,'parkinglane-left-orthogonal'))
277    plror = dest_parking_style_document.adoptNode(parking_dom_cut_style(parktrans_style_document,'parkinglane-right-orthogonal'))
278    pll = dest_parking_style_document.adoptNode(parking_dom_cut_layer(parktrans_style_document,'parkinglane-left'))
279    plr = dest_parking_style_document.adoptNode(parking_dom_cut_layer(parktrans_style_document,'parkinglane-right'))
280
281    things=[pllno,plrno,pllin,plrin,plldi,plrdi,pllor,plror,pll,plr]
282    parking_dom_insert_things_before_layer(dest_parking_style_document,things,'direction_pre_bridges')
283
284    output= dest_parking_style_document.implementation.createLSOutput()
285    output.systemId= dest_parking_style_file
286    output.encoding= 'utf-8'
287    serialiser= dest_parking_style_document.implementation.createLSSerializer()
288    serialiser.write(dest_parking_style_document, output)
289
290    ''' write a "rest" file to check if everything has been cut out
291    output= parktrans_style_document.implementation.createLSOutput()
292    output.systemId= 'rest.xml'
293    output.encoding= 'utf-8'
294    serialiser= parktrans_style_document.implementation.createLSSerializer()
295    serialiser.write(parktrans_style_document, output)
296    '''
297
298def parking_dom_insert_things_before_layer(document,things,here):
299    # insert things after the "leisure" layer
300    els = document.getElementsByTagName("Layer")
301    #print "els="
302    #print els
303    for el in els:
304        #print "layername={ln}".format(ln=el.getAttribute("name"))
305        if el.getAttribute("name")==here:
306            #print "found it"
307            if type(things) is list:
308                for s in things:
309                    el.parentNode.insertBefore(s,el)
310            else:
311                el.parentNode.insertBefore(things,el)
312            return
313    raise 'Layer name not found'
314
315def parking_dom_cut_layer(document,what):
316    els = document.getElementsByTagName("Layer")
317    for el in els:
318        #print "layername={ln}".format(ln=el.getAttribute("name"))
319        if el.getAttribute("name")==what:
320            #print "found it"
321            el.parentNode.removeChild(el)
322            return el
323    raise 'Layer name not found'
324
325def parking_dom_cut_style(document,what):
326    els = document.getElementsByTagName("Style")
327    for el in els:
328        #print "layername={ln}".format(ln=el.getAttribute("name"))
329        if el.getAttribute("name")==what:
330            #print "found it"
331            el.parentNode.removeChild(el)
332            return el
333    raise 'Style name not found'
334
335"""
336./generate_xml.py osm-parking-src.xml    osm-parking.xml    --accept-none --host sql-mapnik --dbname osm_mapnik --prefix planet --inc ./parking-inc --symbols ./parking-symbols/ --world_boundaries /home/project/o/s/m/osm/data/world_boundaries/ --password ''
337./generate_xml.py osm-parking-bw-src.xml osm-parking-bw.xml --accept-none --host sql-mapnik --dbname osm_mapnik --prefix planet --inc ./parking-inc --symbols ./parking-symbols/ --world_boundaries /home/project/o/s/m/osm/data/world_boundaries/ --password ''
338./generate_xml.py osm-parkerr-src.xml    osm-parkerr.xml    --accept-none --host sql-mapnik --dbname osm_mapnik --prefix planet --inc ./parking-inc --symbols ./parking-symbols/ --world_boundaries /home/project/o/s/m/osm/data/world_boundaries/ --password ''
339"""
340
341if __name__ == '__main__':
342    parser = OptionParser()
343    parser.add_option("-s", "--sourcedir", dest="sourcedir", help="path to the source directory", default=".")
344    parser.add_option("-f", "--sourcefile", dest="sourcefile", help="source filename, default is 'osm.xml')", default="osm.xml")
345    parser.add_option("-d", "--destdir", dest="destdir", help="path to the destination directory, further dirs are created within. default is '/tmp'", default="/tmp")
346    (options, args) = parser.parse_args()
347    options['stylename'] = "parktrans"
348    print options
349    main_parktrans(options.__dict__)
350    options['sourcefile'] = "osm-parking-src.xml"
351    options['stylename'] = "parking"
352    main_parking(options.__dict__)
353    sys.exit(0)
Note: See TracBrowser for help on using the repository browser.