# -*- coding: utf-8 -*- from __future__ import print_function, absolute_import, unicode_literals """ Sygic OfflineSpeedCams generator. Convert Speed Camera / Photo Radar from IGO to Sygic. Copyright (C) 2017 Miszel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import csv import sqlite3 import os import re import datetime def igo2sygic(files, igo_types, debug): """ SpeedCamText.txt header line: X, Y, TYPE, SPEED, DIRTYPE, DIRECTION X = longitude Y = latitude TYPE = type of speed camera ( 1 - fixed speed camera locations; 2 - combined red light and speed cameras; 3 - fixed red light camera locations; 4 - section camera positions; 5 - lasers, hand-held radars and other mobile speed camera locations; 6 - railway crossing; 7 - not constant mobile locations) SPEED = speed limit in km/h DIRTYPE = type of direction of the speedcam (0-all directions; 1-one direction; 2-both directions) DIRECTION = direction in degrees (0-North; 90-East) """ speedcams = [] # [[latitude, longitude, speed, type], [...]] for filename in files: if not os.path.exists(filename): continue if debug: print('\n' + filename) with (open(filename, 'rb') if bytes is str else open(filename, mode='r', newline='')) as csvfile: speedcam_csv = csv.reader(csvfile, delimiter=str(','), quotechar=str('"')) for row in speedcam_csv: #omit header if speedcam_csv.line_num == 1 and row[0] == 'X': continue #omit bad lines if len(row) != 6: if debug: print(speedcam_csv.line_num, 'BAD LINE !!!', sep='; ') continue longitude, latitude, kind, speed, dirtype, angle = row[0], row[1], row[2], row[3], row[4], row[5] #is latitude a float? if not, omit record try: float(latitude) except ValueError: if debug: print(speedcam_csv.line_num, 'Y', latitude, sep='; ') continue #is longitude a float? if not, omit record try: float(longitude) except ValueError: if debug: print(speedcam_csv.line_num, 'X', longitude, sep='; ') continue #is speed a integer? if not, try to find or set zero if not speed.isdigit(): #try to find first number in string speed = re.search('\d+|$', speed).group() if not speed.isdigit(): speed = 0 if debug: print(speedcam_csv.line_num, 'SPEED', row[3], speed, sep='; ') if igo_types: #is type a integer? if not, set as normal speed camera - 1 if not kind.isdigit(): kind = '1' if debug: print(speedcam_csv.line_num, 'TYPE', row[2], kind, sep='; ') if kind in igo_types: kind = igo_types[kind] else: if debug and igo_types: print(speedcam_csv.line_num, 'TYPE', row[2], 'not defined in igotypes', sep='; ') continue else: kind = '1' #igo dirtype equals 0 or 2: both ways; dirtype equals 1: single direction both_ways = 0 if int(dirtype) == 1 else 1 #convert to sygic format speedcams.append([int(float(latitude) * 100000), int(float(longitude) * 100000), int(speed), int(kind), int(angle), int(both_ways)]) #sort by latitude, longitude, speed speedcams.sort(key=lambda x: (x[0], x[1], x[2])) print('\nSpeedCameras all: {:,}'.format(len(speedcams))) #eliminate duplicates: #append duplicated speed cameras to radars dict group by location radars = {} #radars[location: latitude,longitude] = [[index, latitude, longitude, speed, kind, angle, both_ways, delete_marker: 0 - ok; 1 - del], [...], [...]] INDEX = 0 SPEED = 3 MARK = 7 speedcams2 = speedcams[:] index1 = len(speedcams2) while speedcams2: index1 -= 1 latitude1, longitude1, speed1, kind1, angle1, both_ways1 = speedcams2.pop() location = str(latitude1) + ',' + str(longitude1) if location in radars: continue index2 = index1 for speedcam2 in reversed(speedcams2): index2 -= 1 latitude2, longitude2, speed2, kind2, angle2, both_ways2 = speedcam2 if latitude1 == latitude2 and longitude1 == longitude2: delete_marker = 0 if location not in radars: radars[location] = [[index1, latitude1, longitude1, speed1, kind1, angle1, both_ways1, delete_marker]] radars[location].append([index2, latitude2, longitude2, speed2, kind2, angle2, both_ways2, delete_marker]) else: break #if exactly the same: leave first, mark rest to delete for duplicates in radars.values(): for idx1 in range(len(duplicates)): for idx2, radar in enumerate(duplicates): if idx2 > idx1 and radar[SPEED] == duplicates[idx1][SPEED]: radar[MARK] = 1 def count2leave(duplicates): return sum(1 for radar in duplicates if radar[MARK] == 0) #one of speed is zero for duplicates in radars.values(): if count2leave(duplicates) > 1: for radar in duplicates: if radar[SPEED] == 0: radar[MARK] = 1 #select lowest speed limit for duplicates in radars.values(): if count2leave(duplicates) > 1: minspeed = min([radar[SPEED] for radar in duplicates if radar[MARK] == 0]) for radar in duplicates: if radar[MARK] == 0 and radar[SPEED] != minspeed: radar[MARK] = 1 if debug: for location, duplicates in radars.items(): print('\n', location, count2leave(duplicates)) for radar in duplicates: print(radar) #delete marked del_list = [radar[INDEX] for duplicates in radars.values() for radar in duplicates if radar[MARK] == 1] del_list.sort(key=int, reverse=True) [speedcams.pop(d) for d in del_list] return speedcams def dat2points(dat_filename): if not os.path.exists(dat_filename): return conn = sqlite3.connect(dat_filename, isolation_level=None) cursor = conn.cursor() cursor.execute('SELECT Latitude, Longitude, SpeedLimit, Type, Angle, BothWays FROM OfflineSpeedcam ORDER BY Latitude, Longitude') return cursor.fetchall() def points2map(speedcams): html_filename = 'offlinespeedcams.dat_' + datetime.datetime.now().strftime('%Y%m%d_%H%M%S') html = [] html.append('') html.append('') html.append('
') html.append('