source: subversion/applications/rendering/parking/mapnik/generate_wifi_layer_xml.py @ 27312

Last change on this file since 27312 was 27307, checked in by kdrangmeister, 8 years ago

changed wifi layer

  • Property svn:mime-type set to text/plain
File size: 12.2 KB
Line 
1# -*- coding: utf-8 -*-
2# by kay
3
4import sys,os,subprocess,shutil
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    'cust': 'b68529',
14    'none': '3f2920',
15    'fee':  '67a1eb',
16    'unkn': 'bc73e2' # purple:'bc73e2' ; bluegreen:'6fc58a'
17    }
18
19def dom_strip_style_and_layer(document,stylename,layername):
20    removeElements=[]
21    # remove <Style name="points"> and <Layer name="amenity-points">
22    els = document.getElementsByTagName("Style")
23    for el in els:
24        if el.getAttribute("name")==stylename:
25            removeElements.append(el)
26    els = document.getElementsByTagName("Layer")
27    for el in els:
28        if el.getAttribute("name")==layername:
29            removeElements.append(el)
30    print "removing the following elements:"
31    print removeElements
32    for el in removeElements:
33        parent = el.parentNode
34        parent.removeChild(el)
35
36def dom_strip_icons(document):
37    dom_strip_style_and_layer(document,"points","amenity-points")
38    dom_strip_style_and_layer(document,"power_line","power_line")
39    dom_strip_style_and_layer(document,"power_minorline","power_minorline")
40    dom_strip_style_and_layer(document,"power_towers","power_towers")
41    dom_strip_style_and_layer(document,"power_poles","power_poles")
42
43def transmogrify_file(sf,dfgrey,dfnoicons):
44    dom= pxdom.getDOMImplementation('')
45    parser= dom.createLSParser(dom.MODE_SYNCHRONOUS, None)
46    parser.domConfig.setParameter('entities', 0) # 1 -> exception if attribute values is set
47    #parser.domConfig.setParameter('disallow-doctype', 1)
48    parser.domConfig.setParameter('pxdom-resolve-resources', 1) # 1 -> replace &xyz; with text
49    document = parser.parseURI(sf)
50
51#    dom_convert_to_grey(document)
52   
53    output= document.implementation.createLSOutput()
54    output.systemId= dfgrey
55    output.encoding= 'utf-8'
56    serialiser= document.implementation.createLSSerializer()
57    serialiser.write(document, output)
58
59"""
60    dom_strip_icons(document)
61   
62    output= document.implementation.createLSOutput()
63    output.systemId= dfnoicons
64    output.encoding= 'utf-8'
65    serialiser= document.implementation.createLSSerializer()
66    serialiser.write(document, output)
67"""
68
69def strip_doctype(f):
70    p = subprocess.Popen(['sed','-i','2,9 d',f]) # -i means 'in place'
71    p.wait()
72
73def create_wifi_icons(source_symbols_dir,dest_symbols_dir):
74    create_wifi_area_icons(source_symbols_dir,dest_symbols_dir)
75    create_wifi_point_icons(source_symbols_dir,dest_symbols_dir)
76   
77def create_wifi_area_icons(source_symbols_dir,dest_symbols_dir):
78    return
79
80
81def create_wifi_point_icons(source_symbols_dir,dest_symbols_dir):
82    tempf = "/tmp/2347856893476512873465.png"
83#    stampf = os.path.join(source_symbols_dir,"wifi_node_stamp.png")
84    # for now there's only the wifi-vending icon
85    copy_files(source_symbols_dir,dest_symbols_dir,['wifi-vending.png'])
86    # wifi nodes
87    for condition in condition_colors.keys():
88        # convert ./original-mapnik/symbols/*.png -fx '0.25*r + 0.62*g + 0.13*b' ./bw-mapnik/symbols/*.png
89        sf = os.path.join(source_symbols_dir,'wifi-source.png')
90        df = os.path.join(dest_symbols_dir,'wifi_node_{cond}.png'.format(cond=condition))
91        colorize_icon(sf,df,condition_colors.get(condition))
92 #       p = subprocess.Popen(['convert','-size','16x16',tempf,stampf,'-compose','Darken','-composite',df])
93  #      print (['convert','-size','16x16',tempf,stampf,'-compose','Darken','-composite',df])
94    #    p.wait()
95
96def copy_files(src,dest,files):
97    for f in files:
98        if type(f) is tuple:
99            shutil.copy2(os.path.join(src,f[0]),os.path.join(dest,f[1]))
100        else:
101            shutil.copy2(os.path.join(src,f),os.path.join(dest,f))
102
103def colorize_icon(sf,df,color):
104    p = subprocess.Popen(['convert',sf,'-fill','#'+color,'-colorize','100',df])
105    p.wait()
106
107def hflip_icon(sf,df):
108    p = subprocess.Popen(['convert',sf,'-flip',df])
109    p.wait()
110
111def stamp_icon(sf,df,stampf):
112    p = subprocess.Popen(['convert',sf,stampf,'-compose','Darken','-composite',df])
113    p.wait()
114
115def add_license_files(dirname):
116    f = open(os.path.join(dirname,"CONTACT"), 'w')
117    f.write("This style is created by kayd@toolserver.org")
118    f.close
119    f = open(os.path.join(dirname,"LICENSE"), 'w')
120    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)")
121    f.close
122
123def main_wifitrans(options):
124    style_name = options['stylename']
125    source_dir = options['sourcedir']
126    source_file = options['sourcefile']
127    #source_symbols_dir_mapnik = os.path.join(source_dir,"symbols")
128    source_symbols_dir_style = os.path.join(source_dir,"wifi-symbols-src")
129    dest_dir = options['destdir']
130
131    # wifitrans - transparent layer to be put on top of mapnik or bw-noicons base layer
132   
133    dest_dir_style = os.path.join(dest_dir,style_name)
134    dest_dir_style_symbols = os.path.join(dest_dir_style,"symbols")
135    dest_file_style = 'osm-{style}.xml'.format(style=style_name)
136    style_file = os.path.join(dest_dir_style,dest_file_style)
137    if not os.path.exists(dest_dir_style_symbols):
138        os.makedirs(dest_dir_style_symbols)
139
140    create_wifi_icons(source_symbols_dir_style,dest_dir_style_symbols)
141    transmogrify_file(os.path.join(source_dir,source_file),style_file,"")
142    strip_doctype(style_file)
143    add_license_files(dest_dir_style)
144
145def main_wifi(options):
146    style_name = options['stylename']
147    source_bwn_dir = options['sourcebwndir']
148    source_bwn_file = options['sourcebwnfile']
149    source_p_dir = options['sourcepdir']
150    source_p_file = options['sourcepfile']
151    source_symbols_dir_style = os.path.join(source_p_dir,"wifi-symbols-src")
152    dest_dir = options['destdir']
153
154    dest_dir_style = os.path.join(dest_dir,style_name)
155    dest_dir_style_symbols = os.path.join(dest_dir_style,"symbols")
156    dest_file_style = 'osm-{style}.xml'.format(style=style_name)
157    style_file = os.path.join(dest_dir_style,dest_file_style)
158    if not os.path.exists(dest_dir_style_symbols):
159        os.makedirs(dest_dir_style_symbols)
160
161    create_wifi_icons(source_symbols_dir_style,dest_dir_style_symbols)
162    merge_bw_noicons_and_wifitrans_style(os.path.join(source_bwn_dir,source_bwn_file),os.path.join(source_p_dir,source_p_file),style_file)
163    #strip_doctype(style_file)
164    add_license_files(dest_dir_style)
165
166def merge_bw_noicons_and_wifitrans_style(bwnoicons_style_file,wifitrans_style_file,dest_wifi_style_file):
167    dom= pxdom.getDOMImplementation('')
168    parser= dom.createLSParser(dom.MODE_SYNCHRONOUS, None)
169    parser.domConfig.setParameter('entities', 0) # 1 -> exception if attribute values is set
170    #parser.domConfig.setParameter('disallow-doctype', 1)
171    parser.domConfig.setParameter('pxdom-resolve-resources', 1) # 1 -> replace &xyz; with text
172    dest_wifi_style_document = parser.parseURI(bwnoicons_style_file)
173    wifitrans_style_document = parser.parseURI(wifitrans_style_file)
174
175    wifi_area_style = dest_wifi_style_document.adoptNode(wifi_dom_cut_style(wifitrans_style_document,'wifi-area'))
176    wifi_area_layer = dest_wifi_style_document.adoptNode(wifi_dom_cut_layer(wifitrans_style_document,'wifi-area'))
177    things=[wifi_area_style,wifi_area_layer]
178    #better put wifi area layer earlier, before all roads
179    wifi_dom_insert_things_before_layer(dest_wifi_style_document,things,'turning_circle-casing')
180    # duplicate the wifi-area layer in order to make it less transparent
181    clone_of_wifi_area_layer = wifi_dom_clone_layer(dest_wifi_style_document,'wifi-area')
182    clone_of_wifi_area_layer.setAttribute('name','wifi-area-double')
183    wifi_dom_insert_things_before_layer(dest_wifi_style_document,clone_of_wifi_area_layer,'turning_circle-casing')
184
185    #add a second wifi area layer on top of the wifi-aisle roads.
186    wifi_area_top_layer = dest_wifi_style_document.adoptNode(wifi_dom_cut_layer(wifitrans_style_document,'wifi-area-top'))
187    things=[wifi_area_top_layer]
188    wifi_dom_insert_things_before_layer(dest_wifi_style_document,things,'direction_pre_bridges')
189
190    # handle the wifi points / nodes
191    wifi_points_style = dest_wifi_style_document.adoptNode(wifi_dom_cut_style(wifitrans_style_document,'wifi-points'))
192    wifi_points_layer = dest_wifi_style_document.adoptNode(wifi_dom_cut_layer(wifitrans_style_document,'wifi-points'))
193    things=[wifi_points_style,wifi_points_layer]
194    wifi_dom_insert_things_before_layer(dest_wifi_style_document,things,'direction_pre_bridges')
195
196    output= dest_wifi_style_document.implementation.createLSOutput()
197    output.systemId= dest_wifi_style_file
198    output.encoding= 'utf-8'
199    serialiser= dest_wifi_style_document.implementation.createLSSerializer()
200    serialiser.write(dest_wifi_style_document, output)
201
202    ''' write a "rest" file to check if everything has been cut out
203    output= wifitrans_style_document.implementation.createLSOutput()
204    output.systemId= 'rest.xml'
205    output.encoding= 'utf-8'
206    serialiser= wifitrans_style_document.implementation.createLSSerializer()
207    serialiser.write(wifitrans_style_document, output)
208    '''
209
210def wifi_dom_insert_things_before_layer(document,things,here):
211    # insert things after the "leisure" layer
212    els = document.getElementsByTagName("Layer")
213    #print "els="
214    #print els
215    for el in els:
216        #print "layername={ln}".format(ln=el.getAttribute("name"))
217        if el.getAttribute("name")==here:
218            #print "found it"
219            if type(things) is list:
220                for s in things:
221                    el.parentNode.insertBefore(s,el)
222            else:
223                el.parentNode.insertBefore(things,el)
224            return
225    raise 'Layer name not found'
226
227def wifi_dom_clone_layer(document,what):
228    els = document.getElementsByTagName("Layer")
229    for el in els:
230        #print "layername={ln}".format(ln=el.getAttribute("name"))
231        if el.getAttribute("name")==what:
232            #print "found it"
233            clone = el.cloneNode(True)
234            return clone
235    raise BaseException('Layer name {ln} not found'.format(ln=what))
236
237def wifi_dom_cut_layer(document,what):
238    els = document.getElementsByTagName("Layer")
239    for el in els:
240        #print "layername={ln}".format(ln=el.getAttribute("name"))
241        if el.getAttribute("name")==what:
242            #print "found it"
243            el.parentNode.removeChild(el)
244            return el
245    raise BaseException('Layer name {ln} not found'.format(ln=what))
246
247def wifi_dom_cut_style(document,what):
248    els = document.getElementsByTagName("Style")
249    for el in els:
250        #print "layername={ln}".format(ln=el.getAttribute("name"))
251        if el.getAttribute("name")==what:
252            #print "found it"
253            el.parentNode.removeChild(el)
254            return el
255    raise BaseException('Style name {sn} not found'.format(sn=what))
256
257"""
258./generate_xml.py osm-wifi-src.xml    osm-wifi.xml    --accept-none --host sql-mapnik --dbname osm_mapnik --prefix planet --inc ./wifi-inc --symbols ./wifi-symbols/ --world_boundaries /home/project/o/s/m/osm/data/world_boundaries/ --password ''
259./generate_xml.py osm-wifi-bw-src.xml osm-wifi-bw.xml --accept-none --host sql-mapnik --dbname osm_mapnik --prefix planet --inc ./wifi-inc --symbols ./wifi-symbols/ --world_boundaries /home/project/o/s/m/osm/data/world_boundaries/ --password ''
260./generate_xml.py osm-parkerr-src.xml    osm-parkerr.xml    --accept-none --host sql-mapnik --dbname osm_mapnik --prefix planet --inc ./wifi-inc --symbols ./wifi-symbols/ --world_boundaries /home/project/o/s/m/osm/data/world_boundaries/ --password ''
261"""
262
263if __name__ == '__main__':
264    parser = OptionParser()
265    parser.add_option("-s", "--sourcedir", dest="sourcedir", help="path to the source directory", default=".")
266    parser.add_option("-f", "--sourcefile", dest="sourcefile", help="source filename, default is 'osm.xml')", default="osm.xml")
267    parser.add_option("-d", "--destdir", dest="destdir", help="path to the destination directory, further dirs are created within. default is '/tmp'", default="/tmp")
268    (options, args) = parser.parse_args()
269    options['stylename'] = "wifitrans"
270    print options
271    main_wifitrans(options.__dict__)
272    options['sourcefile'] = "osm-wifi-src.xml"
273    options['stylename'] = "wifi"
274    main_wifi(options.__dict__)
275    sys.exit(0)
Note: See TracBrowser for help on using the repository browser.