migration to python3

Signed-off-by: Evgeniy A. Dushistov <dushistov@mail.ru>
This commit is contained in:
Evgeniy A. Dushistov 2021-05-02 17:38:52 +03:00 committed by Alexander Borsuk
parent cbaff545dd
commit 967fcbc17f
6 changed files with 52 additions and 47 deletions

View file

@ -4,6 +4,7 @@ import os
import csv
import sys
import itertools
import functools
from multiprocessing import Pool
from collections import OrderedDict
import mapcss.webcolors
@ -69,7 +70,7 @@ def query_style(args):
cltags["addr:flats"] = "addr:flats"
results = []
for zoom in xrange(minzoom, maxzoom + 1):
for zoom in range(minzoom, maxzoom + 1):
runtime_conditions_arr = []
# Get runtime conditions which are used for class 'cl' on zoom 'zoom'
@ -92,7 +93,7 @@ def query_style(args):
linestyle = style.get_style_dict(clname, "line", cltags, zoom, olddict=zstyle, filter_by_runtime_conditions=runtime_conditions)
zstyle = linestyle
areastyle = style.get_style_dict(clname, "area", cltags, zoom, olddict=zstyle, filter_by_runtime_conditions=runtime_conditions)
for st in areastyle.values():
for st in list(areastyle.values()):
if "icon-image" in st or 'symbol-shape' in st or 'symbol-image' in st:
has_icons_for_areas = True
break
@ -101,7 +102,7 @@ def query_style(args):
nodestyle = style.get_style_dict(clname, "node", cltags, zoom, olddict=zstyle, filter_by_runtime_conditions=runtime_conditions)
zstyle = nodestyle
results.append((cl, zoom, has_icons_for_areas, runtime_conditions, zstyle.values()))
results.append((cl, zoom, has_icons_for_areas, runtime_conditions, list(zstyle.values())))
return results
@ -176,7 +177,7 @@ def komap_mapswithme(options):
if int(row[5]) < cnt:
raise Exception('Wrong type id: {0}'.format(';'.join(row)))
while int(row[5]) > cnt:
print >> types_file, "mapswithme"
print("mapswithme", file=types_file)
cnt += 1
cnt += 1
@ -199,13 +200,13 @@ def komap_mapswithme(options):
class_order.append(cl)
unique_types_check.add(cl)
# Mark original type to distinguish it among replacing types.
print >> types_file, "*" + row[0]
print("*" + row[0], file=types_file)
else:
# compatibility mode
if row[6]:
print >> types_file, row[6]
print(row[6], file=types_file)
else:
print >> types_file, "mapswithme"
print("mapswithme", file=types_file)
class_tree[cl] = row[0]
class_order.sort()
types_file.close()
@ -213,7 +214,7 @@ def komap_mapswithme(options):
# Get all mapcss static tags which are used in mapcss-mapping.csv
# This is a dict with main_tag flags (True = appears first in types)
mapcss_static_tags = {}
for v in classificator.values():
for v in list(classificator.values()):
for i, t in enumerate(v.keys()):
mapcss_static_tags[t] = mapcss_static_tags.get(t, True) and i == 0
@ -242,7 +243,7 @@ def komap_mapswithme(options):
raw_style_colors = style.get_colors()
if raw_style_colors is not None:
unique_style_colors = set()
for k in raw_style_colors.keys():
for k in list(raw_style_colors.keys()):
unique_style_colors.add(k[:k.rindex('-')])
for k in unique_style_colors:
style_colors[k] = mwm_encode_color(colors, raw_style_colors, k)
@ -265,7 +266,7 @@ def komap_mapswithme(options):
imapfunc = itertools.imap
if style_colors:
for k, v in style_colors.iteritems():
for k, v in style_colors.items():
color_proto = ColorElementProto()
color_proto.name = k
color_proto.color = v
@ -298,7 +299,7 @@ def komap_mapswithme(options):
has_icons = False
has_fills = False
for st in zstyle:
st = dict([(k, v) for k, v in st.iteritems() if str(v).strip(" 0.")])
st = dict([(k, v) for k, v in st.items() if str(v).strip(" 0.")])
if 'width' in st or 'pattern-image' in st:
has_lines = True
if 'icon-image' in st or 'symbol-shape' in st or 'symbol-image' in st:
@ -508,17 +509,17 @@ def komap_mapswithme(options):
if options.txt:
drules_txt = open(os.path.join(options.outfile + '.txt'), "wb")
drules_txt.write(unicode(drules))
drules_txt.write(str(drules).encode())
drules_txt.close()
# Write classificator.txt and visibility.txt files
visnodes = set()
for k, v in visibility.iteritems():
for k, v in visibility.items():
vis = k.split("|")
for i in range(1, len(vis) - 1):
visnodes.add("|".join(vis[0:i]) + "|")
viskeys = list(set(visibility.keys() + list(visnodes)))
viskeys = list(set(list(visibility.keys()) + list(visnodes)))
def cmprepl(a, b):
if a == b:
@ -528,7 +529,7 @@ def komap_mapswithme(options):
if a > b:
return 1
return -1
viskeys.sort(cmprepl)
viskeys.sort(key=functools.cmp_to_key(cmprepl))
visibility_file = open(os.path.join(ddir, 'visibility.txt'), "w")
classificator_file = open(os.path.join(ddir, 'classificator.txt'), "w")
@ -536,18 +537,18 @@ def komap_mapswithme(options):
oldoffset = ""
for k in viskeys:
offset = " " * (k.count("|") - 1)
for i in range(len(oldoffset) / 4, len(offset) / 4, -1):
print >> visibility_file, " " * i + "{}"
print >> classificator_file, " " * i + "{}"
for i in range(int(len(oldoffset) / 4), int(len(offset) / 4), -1):
print(" " * i + "{}", file=visibility_file)
print(" " * i + "{}", file=classificator_file)
oldoffset = offset
end = "-"
if k in visnodes:
end = "+"
print >> visibility_file, offset + k.split("|")[-2] + " " + visibility.get(k, "0" * (options.maxzoom + 1)) + " " + end
print >> classificator_file, offset + k.split("|")[-2] + " " + end
for i in range(len(offset) / 4, 0, -1):
print >> visibility_file, " " * i + "{}"
print >> classificator_file, " " * i + "{}"
print(offset + k.split("|")[-2] + " " + visibility.get(k, "0" * (options.maxzoom + 1)) + " " + end, file=visibility_file)
print(offset + k.split("|")[-2] + " " + end, file=classificator_file)
for i in range(int(len(offset) / 4), 0, -1):
print(" " * i + "{}", file=visibility_file)
print(" " * i + "{}", file=classificator_file)
visibility_file.close()
classificator_file.close()

View file

@ -103,6 +103,9 @@ class Condition:
def __eq__(self, a):
return (self.params == a.params) and (self.type == a.type)
def __lt__(self, a):
return (self.params < a.params) or (self.type < a.type)
def Number(tt):
"""
Wrap float() not to produce exceptions

View file

@ -44,8 +44,11 @@ class Eval():
# print self.expr_text
tags = set([])
def tags_add(x):
tags.add(x)
return 0
a = eval(self.expr, {}, {
"tag": lambda x: max([tags.add(x), 0]),
"tag": lambda x: tags_add(x),
"prop": lambda x: 0,
"num": lambda x: 0,
"metric": fake_compute,
@ -176,6 +179,6 @@ def m_metric(x, t):
if __name__ == "__main__":
a = Eval(""" eval( any( metric(tag("height")), metric ( num(tag("building:levels")) * 3), metric("1m"))) """)
print repr(a)
print a.compute({"building:levels": "3"})
print a.extract_tags()
print(repr(a))
print(a.compute({"building:levels": "3"}))
print(a.extract_tags())

View file

@ -16,17 +16,17 @@
# along with kothic. If not, see <http://www.gnu.org/licenses/>.
from Rule import Rule
from webcolors.webcolors import whatever_to_cairo as colorparser
from webcolors.webcolors import cairo_to_hex
from Eval import Eval
from Condition import *
from .Rule import Rule
from .webcolors.webcolors import whatever_to_cairo as colorparser
from .webcolors.webcolors import cairo_to_hex
from .Eval import Eval
from .Condition import *
TYPE_EVAL = type(Eval())
def make_nice_style(r):
ra = {}
for a, b in r.iteritems():
for a, b in r.items():
"checking and nicifying style table"
if type(b) == TYPE_EVAL:
ra[a] = b
@ -101,7 +101,7 @@ class StyleChooser:
break
if self.has_evals and "*" not in a:
for s in self.styles:
for v in s.values():
for v in list(s.values()):
if type(v) == self.eval_type:
a.update(v.extract_tags())
if "*" in a or len(a) == 0:
@ -165,13 +165,13 @@ class StyleChooser:
for r in self.styles:
if self.has_evals:
ra = {}
for a, b in r.iteritems():
for a, b in r.items():
"calculating eval()'s"
if type(b) == self.eval_type:
combined_style = {}
for t in sl:
combined_style.update(t)
for p, q in combined_style.iteritems():
for p, q in combined_style.items():
if "color" in p:
combined_style[p] = cairo_to_hex(q)
b = b.compute(tags, combined_style, xscale, zscale)
@ -267,7 +267,7 @@ class StyleChooser:
rb = []
for r in a:
ra = {}
for a, b in r.iteritems():
for a, b in r.items():
a = a.strip()
b = b.strip()
if a == "casing-width":

View file

@ -18,8 +18,8 @@
import re
import os
import logging
from StyleChooser import StyleChooser
from Condition import Condition
from .StyleChooser import StyleChooser
from .Condition import Condition
NEEDED_KEYS = set(["width", "casing-width", "fill-color", "fill-image", "icon-image", "text", "extrude",
@ -127,7 +127,7 @@ class MapCSS():
def restore_choosers_order(self, type):
ethalon_choosers = self.choosers_by_type[type]
for tag, choosers_for_tag in self.choosers_by_type_and_tag[type].items():
for tag, choosers_for_tag in list(self.choosers_by_type_and_tag[type].items()):
tmp = []
for ec in ethalon_choosers:
if ec in choosers_for_tag:

View file

@ -198,7 +198,7 @@ def _reversedict(d):
dictionary, returns a new dictionary with keys and values swapped.
"""
return dict(zip(d.values(), d.keys()))
return dict(list(zip(list(d.values()), list(d.keys()))))
HEX_COLOR_RE = re.compile(r'^#([a-fA-F0-9]|[a-fA-F0-9]{3}|[a-fA-F0-9]{6})$')
@ -454,7 +454,7 @@ def normalize_hex(hex_value):
except AttributeError:
raise ValueError("'%s' is not a valid hexadecimal color value." % hex_value)
if len(hex_digits) == 3:
hex_digits = ''.join(map(lambda s: 2 * s, hex_digits))
hex_digits = ''.join([2 * s for s in hex_digits])
elif len(hex_digits) == 1:
hex_digits = hex_digits * 6
return '#%s' % hex_digits.lower()
@ -648,8 +648,7 @@ def hex_to_rgb(hex_value):
"""
hex_digits = normalize_hex(hex_value)
return tuple(map(lambda s: int(s, 16),
(hex_digits[1:3], hex_digits[3:5], hex_digits[5:7])))
return tuple([int(s, 16) for s in (hex_digits[1:3], hex_digits[3:5], hex_digits[5:7])])
def hex_to_rgb_percent(hex_value):
@ -716,7 +715,7 @@ def rgb_to_hex(rgb_triplet):
'#2138c0'
"""
return '#%02x%02x%02x' % rgb_triplet
return '#%02x%02x%02x' % (int(rgb_triplet[0]), int(rgb_triplet[1]), int(rgb_triplet[2]))
def rgb_to_rgb_percent(rgb_triplet):
@ -750,8 +749,7 @@ def rgb_to_rgb_percent(rgb_triplet):
# from 0 through 4, as well as 0 itself.
specials = {255: '100%', 128: '50%', 64: '25%',
32: '12.5%', 16: '6.25%', 0: '0%'}
return tuple(map(lambda d: specials.get(d, '%.02f%%' % ((d / 255.0) * 100)),
rgb_triplet))
return tuple([specials.get(d, '%.02f%%' % ((d / 255.0) * 100)) for d in rgb_triplet])
######################################################################