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

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

change deployment

  • Property svn:mime-type set to text/plain
File size: 11.3 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#import colorsys
9
10condition_colors = {
11    'free': '7fff00',
12    'disc': '50a100',
13    'cust': 'b68529',
14    'resi': '785534',
15    'priv': '3f2920',
16    'fee':  '67a1eb',
17    'unkn': 'bc73e2'
18    }
19
20forbidden_colors = {
21    'nopa': 'f8b81f',
22    'nost': 'f85b1f',
23    'fire': 'f81f1f'
24    }
25
26
27"""
28def dom_convert_to_grey(document):
29    els = document.getElementsByTagName("CssParameter")
30    #print "els=",els
31    for el in els:
32        at = el.getAttribute("name")
33        if at=="stroke" or at=="fill":
34            col=el.firstChild.nodeValue
35            bw=rgb_to_css(color_to_bw(parse_color(col)))
36            print "converted {typ} from {a} to {bw}." .format(typ=at,a=col,bw=bw)
37            el.firstChild.nodeValue=bw
38
39    #<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">
40    els = document.getElementsByTagName("Map")
41    for el in els:
42        col = el.getAttribute("bgcolor")
43        assert(col!='')
44        assert(col!=None)
45        bw=rgb_to_css(color_to_bw(parse_color(col)))
46        print "converted {typ} from {a} to {bw}." .format(typ='bgcolor',a=col,bw=bw)
47        el.setAttribute("bgcolor",bw)
48
49    #<TextSymbolizer ... fill="#6699cc"/>
50    els = document.getElementsByTagName("TextSymbolizer")
51    for el in els:
52        col = el.getAttribute("fill")
53        assert(col!='')
54        assert(col!=None)
55        bw=rgb_to_css(color_to_bw(parse_color(col)))
56        print "converted {typ} from {a} to {bw}." .format(typ='TS-fill',a=col,bw=bw)
57        el.setAttribute("fill",bw)
58        #<TextSymbolizer halo_fill="#fed7a5"/> (optional)
59        col = el.getAttribute("halo_fill")
60        assert(col!=None)
61        if col!='':
62            bw=rgb_to_css(color_to_bw(parse_color(col)))
63            print "converted {typ} from {a} to {bw}." .format(typ='TS-halo_fill',a=col,bw=bw)
64            el.setAttribute("halo_fill",bw)
65"""
66
67def dom_strip_style_and_layer(document,stylename,layername):
68    removeElements=[]
69    # remove <Style name="points"> and <Layer name="amenity-points">
70    els = document.getElementsByTagName("Style")
71    for el in els:
72        if el.getAttribute("name")==stylename:
73            removeElements.append(el)
74    els = document.getElementsByTagName("Layer")
75    for el in els:
76        if el.getAttribute("name")==layername:
77            removeElements.append(el)
78    print removeElements
79    for el in removeElements:
80        parent = el.parentNode
81        parent.removeChild(el)
82
83def dom_strip_icons(document):
84    dom_strip_style_and_layer(document,"points","amenity-points")
85    dom_strip_style_and_layer(document,"power_line","power_line")
86    dom_strip_style_and_layer(document,"power_minorline","power_minorline")
87    dom_strip_style_and_layer(document,"power_towers","power_towers")
88    dom_strip_style_and_layer(document,"power_poles","power_poles")
89
90def transmogrify_file(sf,dfgrey,dfnoicons):
91    dom= pxdom.getDOMImplementation('')
92    parser= dom.createLSParser(dom.MODE_SYNCHRONOUS, None)
93    parser.domConfig.setParameter('entities', 0) # 1 -> exception if attribute values is set
94    #parser.domConfig.setParameter('disallow-doctype', 1)
95    parser.domConfig.setParameter('pxdom-resolve-resources', 1) # 1 -> replace &xyz; with text
96    document = parser.parseURI(sf)
97
98#    dom_convert_to_grey(document)
99   
100    output= document.implementation.createLSOutput()
101    output.systemId= dfgrey
102    output.encoding= 'utf-8'
103    serialiser= document.implementation.createLSSerializer()
104    serialiser.write(document, output)
105
106"""
107    dom_strip_icons(document)
108   
109    output= document.implementation.createLSOutput()
110    output.systemId= dfnoicons
111    output.encoding= 'utf-8'
112    serialiser= document.implementation.createLSSerializer()
113    serialiser.write(document, output)
114"""
115
116def strip_doctype(f):
117    p = subprocess.Popen(['sed','-i','2,9 d',f]) # -i means 'in place'
118    p.wait()
119
120def create_parking_icons(source_symbols_dir,dest_symbols_dir):
121    create_parking_lane_icons(source_symbols_dir,dest_symbols_dir)
122    create_parking_area_icons(source_symbols_dir,dest_symbols_dir)
123   
124def create_parking_lane_icons(source_symbols_dir,dest_symbols_dir):
125    # first create mirror images (from left to right)
126    image_files = os.listdir(source_symbols_dir)
127    image_files = [f for f in image_files if f.startswith('park-l') and f.endswith('png')]
128    for f in image_files:
129        sf = os.path.join(source_symbols_dir,f)
130        df = os.path.join(source_symbols_dir,f) # this is changed so that we write in the source dir
131        hflip_icon(sf,df.replace('-l','-r'))
132
133    # then, create the colors
134    image_files = os.listdir(source_symbols_dir)
135    image_files = [f for f in image_files if f.endswith('source.png')]
136    for f in image_files:
137        # convert ./original-mapnik/symbols/*.png -fx '0.25*r + 0.62*g + 0.13*b' ./bw-mapnik/symbols/*.png
138        sf = os.path.join(source_symbols_dir,f)
139        df = os.path.join(dest_symbols_dir,f)
140        if 'n-' in f:      # then it's a non-parking thing
141            for c in forbidden_colors.iterkeys():
142                colorize_icon(sf,df.replace('source',c),forbidden_colors.get(c))
143        else:
144            for c in condition_colors.iterkeys():
145                colorize_icon(sf,df.replace('source',c),condition_colors.get(c))
146
147def create_parking_area_icons(source_symbols_dir,dest_symbols_dir):
148    df = os.path.join(dest_symbols_dir,"parking_area_source.png")
149    stampf = os.path.join(source_symbols_dir,"parking_area_stamp.png")
150    for c in condition_colors.iterkeys():
151        p = subprocess.Popen(['convert','-size','16x16','xc:#'+condition_colors.get(c),stampf,'-compose','Darken','-composite',df.replace('source',c)])
152        p.wait()
153
154def create_parking_area_icons_delete(source_symbols_dir,dest_symbols_dir):
155    image_files = os.listdir(source_symbols_dir)
156    image_files = [f for f in image_files if f.startswith('parking_area') and f.endswith('source.png')]
157    print "all image files:", image_files
158    for f in image_files:
159        sf = os.path.join(source_symbols_dir,f)
160        df = os.path.join(dest_symbols_dir,f)
161        stampf = sf.replace('source','stamp')
162        print "stampf", stampf
163        for c in condition_colors.iterkeys():
164            colorize_icon(sf,df.replace('source',c),condition_colors.get(c))
165            stamp_icon(df.replace('source',c),df.replace('source',c),stampf)
166
167def colorize_icon(sf,df,color):
168    p = subprocess.Popen(['convert',sf,'-fill','#'+color,'-colorize','100',df])
169    p.wait()
170
171def hflip_icon(sf,df):
172    p = subprocess.Popen(['convert',sf,'-flip',df])
173    p.wait()
174
175def stamp_icon(sf,df,stampf):
176    p = subprocess.Popen(['convert',sf,stampf,'-compose','Darken','-composite',df])
177    p.wait()
178
179def add_license_files(dirname):
180    f = open(os.path.join(dirname,"CONTACT"), 'w')
181    f.write("This style is created by kayd@toolserver.org")
182    f.close
183    f = open(os.path.join(dirname,"LICENSE"), 'w')
184    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)")
185    f.close
186
187def main_parktrans(options):
188    style_name = options['stylename']
189    source_dir = options['sourcedir']
190    source_file = options['sourcefile']
191    #source_symbols_dir_mapnik = os.path.join(source_dir,"symbols")
192    source_symbols_dir_style = os.path.join(source_dir,"parking-symbols-src")
193    dest_dir = options['destdir']
194
195    # parktrans - transparent layer to be put on top of mapnik or bw-noicons base layer
196   
197    dest_dir_style = os.path.join(dest_dir,style_name)
198    dest_dir_style_symbols = os.path.join(dest_dir_style,"symbols")
199    dest_file_style = 'osm-{style}.xml'.format(style=style_name)
200    style_file = os.path.join(dest_dir_style,dest_file_style)
201    if not os.path.exists(dest_dir_style_symbols):
202        os.makedirs(dest_dir_style_symbols)
203
204    create_parking_icons(source_symbols_dir_style,dest_dir_style_symbols)
205    transmogrify_file(os.path.join(source_dir,source_file),style_file,"")
206    strip_doctype(style_file)
207    add_license_files(dest_dir_style)
208
209def main_parking(options):
210    style_name = options['stylename']
211    source_dir = options['sourcedir']
212    source_file = options['sourcefile']
213    source_symbols_dir_style = os.path.join(source_dir,"parking-symbols-src")
214    dest_dir = options['destdir']
215
216    # parking - bw-noicons background ans parking information on top - single layer containing all
217
218    dest_dir_style = os.path.join(dest_dir,style_name)
219    dest_dir_style_symbols = os.path.join(dest_dir_style,"symbols")
220    dest_file_style = 'osm-{style}.xml'.format(style=style_name)
221    style_file = os.path.join(dest_dir_style,dest_file_style)
222    if not os.path.exists(dest_dir_style_symbols):
223        os.makedirs(dest_dir_style_symbols)
224
225    create_parking_icons(source_symbols_dir_style,dest_dir_style_symbols)
226    transmogrify_file(os.path.join(source_dir,source_file),style_file,"")
227    strip_doctype(style_file)
228    add_license_files(dest_dir_style)
229
230def main_parking_neu(options):
231    style_name = options['stylename']
232    source_dir = options['sourcedir']
233    source_file = options['sourcefile']
234    source_symbols_dir_style = os.path.join(source_dir,"parking-symbols-src")
235    dest_dir = options['destdir']
236
237    dest_dir_style = os.path.join(dest_dir,style_name)
238    dest_dir_style_symbols = os.path.join(dest_dir_style,"symbols")
239    dest_file_style = 'osm-parking-neu.xml'
240    style_file = os.path.join(dest_dir_style,dest_file_style)
241    if not os.path.exists(dest_dir_style_symbols):
242        os.makedirs(dest_dir_style_symbols)
243
244    create_parking_icons(source_symbols_dir_style,dest_dir_style_symbols)
245    transmogrify_file(os.path.join(source_dir,source_file),style_file,"")
246    strip_doctype(style_file)
247    add_license_files(dest_dir_style)
248
249   
250
251"""
252./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 ''
253./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 ''
254./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 ''
255"""
256
257if __name__ == '__main__':
258    parser = OptionParser()
259    parser.add_option("-s", "--sourcedir", dest="sourcedir", help="path to the source directory", default=".")
260    parser.add_option("-f", "--sourcefile", dest="sourcefile", help="source filename, default is 'osm.xml')", default="osm.xml")
261    parser.add_option("-d", "--destdir", dest="destdir", help="path to the destination directory, further dirs are created within. default is '/tmp'", default="/tmp")
262    (options, args) = parser.parse_args()
263    options['stylename'] = "parktrans"
264    print options
265    main_parktrans(options.__dict__)
266    options['sourcefile'] = "osm-parking-src.xml"
267    options['stylename'] = "parking"
268    main_parking(options.__dict__)
269    sys.exit(0)
Note: See TracBrowser for help on using the repository browser.