Interactive interface for browsing global, full-resolution satellite imagery
remove python.2.7 #1682
Benjamin King02e5bff7f852
diff --git a/tasks/buildOptions.sh b/tasks/buildOptions.shindex 501b5d02e..58d1df40f 100755--- a/tasks/buildOptions.sh+++ b/tasks/buildOptions.sh@@ -8,8 +8,7 @@ SRC_DIR="$BASE/config/default"OPT_DIR="$BASE/config/default"BUILD_DIR="$BASE/build/options-build"DEST_DIR="$BASE/build/options"-PYTHON_SCRIPTS_DIR="$TASKS_DIR/python2.7"-PYTHON_VERSION="$(python -V 2>&1)"+PYTHON_SCRIPTS_DIR="$TASKS_DIR/python3"# If there is an active directory, use instead of defaults@@ -17,9 +16,7 @@ if [ -d "$BASE/config/active" ]; thenSRC_DIR="$BASE/config/active"OPT_DIR="$BASE/config/active"fi-if [command -v python3 &>/dev/null] || [[ $PYTHON_VERSION = *"Python 3"* ]]; then- PYTHON_SCRIPTS_DIR="$TASKS_DIR/python3"-fi+# If $IGNORE_ERRORS is true, don't fail on errors[ "$IGNORE_ERRORS" ] || set -ediff --git a/tasks/python2.7/copyVectorStyles.py b/tasks/python2.7/copyVectorStyles.pydeleted file mode 100755index 95c499a12..000000000--- a/tasks/python2.7/copyVectorStyles.py+++ /dev/null@@ -1,59 +0,0 @@-#!/usr/bin/env python--from optparse import OptionParser-import os-import sys-import json-import shutil--prog = os.path.basename(__file__)-base_dir = os.path.join(os.path.dirname(__file__), "..")-version = "3.0.0"-help_description = """\-Converts vector styles to JSON files-"""--parser = OptionParser(usage="Usage: %s <config_file> <vectorstyles_input_dir> <output_dir>" % prog,- version="%s version %s" % (prog, version),- epilog=help_description)--(options, args) = parser.parse_args()-if len(args) != 3:- parser.error("Invalid number of arguments")--config_file = args[0]-vectorstyles_input_dir = args[1]-output_dir = args[2]--with open(config_file) as fp:- config = json.load(fp)-skips = config.get("skipPalettes", [])--def copy_file(file):- input_file = os.path.join(root, file)- id = os.path.splitext(os.path.basename(input_file))[0]- if id in skips:- sys.stderr.write("%s: WARN: [%s] %s\n" % (prog, input_file,- "Skipping"))- return-- if input_file.endswith('.json'):- shutil.copy(input_file, output_dir)--# Main-file_count = 0-error_count = 0--for root, dirs, files in os.walk(vectorstyles_input_dir):- for file in files:- try:- file_count += 1- copy_file(file)- except Exception as e:- sys.stderr.write("%s: ERROR: [%s] %s\n" % (prog, file, str(e)))- error_count += 1--print "%s: %d error(s), %d file(s)" % (prog, error_count, file_count)--if error_count > 0:- sys.exit(1)diff --git a/tasks/python2.7/extractConfigFromWMTS.py b/tasks/python2.7/extractConfigFromWMTS.pydeleted file mode 100755index c9c1cd6d9..000000000--- a/tasks/python2.7/extractConfigFromWMTS.py+++ /dev/null@@ -1,237 +0,0 @@-#!/usr/bin/env python--from datetime import datetime, date, timedelta-import json-from optparse import OptionParser-import os-import sys-import xmltodict-import isodate-from processTemporalLayer import process_temporal-from collections import OrderedDict--prog = os.path.basename(__file__)-base_dir = os.path.join(os.path.dirname(__file__), "..")-version = "2.0.0"-help_description = """\-Extracts configuration information from a WMTS GetCapabilities file.-"""--parser = OptionParser(usage="Usage: %s <config_file> <input_dir> <output_dir> <colormaps_dir>" % prog,- version="%s version %s" % (prog, version),- epilog=help_description)-(options, args) = parser.parse_args()--if len(args) != 4:- parser.error("Invalid number of arguments")--config_file = args[0]-input_dir = args[1]-output_dir = args[2]-colormaps_dir = args[3]--with open(config_file) as fp:- config = json.load(fp)--tolerant = config.get("tolerant", False)-if not "wv-options-wmts" in config:- sys.exit(0)--if not os.path.exists(output_dir):- os.makedirs(output_dir)--entries = config["wv-options-wmts"]-skip = []-# Looks like this is for a list of layers needed to be skipped from the GC-if "skip" in config:- skip = config["skip"]--total_layer_count = 0-total_warning_count = 0-total_error_count = 0--json_options = {}-json_options["indent"] = 2-json_options["separators"] = (',', ': ')--class SkipException(Exception):- pass--def process_layer(gc_layer, wv_layers, colormaps):- ident = gc_layer["ows:Identifier"]- if ident in skip:- print "%s: skipping" % ident- raise SkipException(ident)-- wv_layers[ident] = {}- wv_layer = wv_layers[ident]- wv_layer["id"] = ident- wv_layer["type"] = "wmts"- wv_layer["format"] = gc_layer["Format"]-- # Extract start and end dates- if "Dimension" in gc_layer:- dimension = gc_layer["Dimension"]- if dimension["ows:Identifier"] == "Time":- wv_layer = process_temporal(wv_layer, dimension["Value"])- # Extract matrix set- matrixSet = gc_layer["TileMatrixSetLink"]["TileMatrixSet"]- wv_layer["projections"] = {- entry["projection"]: {- "source": entry["source"],- "matrixSet": matrixSet- }- }-- # Vector data links- if "ows:Metadata" in gc_layer and gc_layer["ows:Metadata"] is not None:- for item in gc_layer["ows:Metadata"]:- if "@xlink:role" not in item:- raise KeyError("No xlink:role")- schema_version = item["@xlink:role"]-- if schema_version == "http://earthdata.nasa.gov/gibs/metadata-type/layer/1.0":- vector_data_link = item["@xlink:href"]- vector_data_file = os.path.basename(vector_data_link)- vector_data_id = os.path.splitext(vector_data_file)[0]- wv_layer["vectorData"] = {- "id": vector_data_id- }-- # Colormap links- if "ows:Metadata" in gc_layer and gc_layer["ows:Metadata"] is not None:- if "skipPalettes" in config and ident in config["skipPalettes"]:- sys.stderr.write("%s: WARNING: Skipping palette for %s\n" % (- prog, ident))- global total_warning_count- total_warning_count += 1- else:- for item in gc_layer["ows:Metadata"]:- if "@xlink:role" not in item:- raise KeyError("No xlink:role")- schema_version = item["@xlink:role"]-- if schema_version == "http://earthdata.nasa.gov/gibs/metadata-type/colormap/1.3":- colormap_link = item["@xlink:href"]- colormap_file = os.path.basename(colormap_link)- colormap_id = os.path.splitext(colormap_file)[0]- wv_layer["palette"] = {- "id": colormap_id- }- elif schema_version == "http://earthdata.nasa.gov/gibs/metadata-type/mapbox-gl-style/1.0":- vectorstyle_link = item["@xlink:href"]- vectorstyle_file = os.path.basename(vectorstyle_link)- vectorstyle_id = os.path.splitext(vectorstyle_file)[0]- wv_layer["vectorStyle"] = {- "id": vectorstyle_id- }--def process_entry(entry, colormaps):- layer_count = 0- warning_count = 0- error_count = 0- wv = {- "layers": {},- "sources": {}- }- wv_matrix_sets = {}- wv["sources"][entry["source"]] = {- "matrixSets": wv_matrix_sets- }-- input_file = os.path.join(input_dir, entry["from"])- gc_id = os.path.basename(input_file)- try:- with open(input_file) as fp:- xml = fp.read()- gc = xmltodict.parse(xml)- except Exception as e:- if tolerant:- sys.stderr.write("%s: WARN: [%s] Unable to get GC: %s\n" %- (prog, input_file, str(e)))- warning_count += 1- else:- sys.stderr.write("%s: ERROR: [%s] Unable to get GC: %s\n" %- (prog, input_file, str(e)))- error_count += 1- return [error_count, warning_count, layer_count]-- gc_contents = gc["Capabilities"]["Contents"]- wv_layers = wv["layers"]-- if gc_contents is None or "Layer" not in gc_contents:- error_count += 1- sys.stderr.write("%s: ERROR: [%s] %s\n" % (prog, gc_id, "No layers"))- return [error_count, warning_count, layer_count]-- if(type(gc["Capabilities"]["Contents"]["Layer"]) is OrderedDict):- gc_layer = gc["Capabilities"]["Contents"]["Layer"]- ident = gc_layer["ows:Identifier"]- try:- layer_count += 1- process_layer(gc_layer, wv_layers, colormaps)- except SkipException as se:- warning_count += 1- sys.stderr.write("%s: WARNING: [%s] Skipping\n" % (prog, ident))- except Exception as e:- error_count += 1- sys.stderr.write("%s: ERROR: [%s:%s] %s\n" % (prog, gc_id,- ident, str(e)))- else:- for gc_layer in gc_contents["Layer"]:- ident = gc_layer["ows:Identifier"]- try:- layer_count += 1- process_layer(gc_layer, wv_layers, colormaps)- except SkipException as se:- warning_count += 1- sys.stderr.write("%s: WARNING: [%s] Skipping\n" % (prog, id))- except Exception as e:- error_count += 1- sys.stderr.write("%s: ERROR: [%s:%s] %s\n" % (prog, gc_id,- ident, str(e)))-- def process_matrix_set(gc_matrix_set):- ident = gc_matrix_set["ows:Identifier"]- zoom_levels = len(gc_matrix_set["TileMatrix"])- resolutions = []- max_resolution = entry["maxResolution"]- for zoom in xrange(0, zoom_levels):- resolutions = resolutions + [max_resolution / (2 ** zoom)]- wv_matrix_sets[ident] = {- "id": ident,- "maxResolution": max_resolution,- "resolutions": resolutions,- "tileSize": [- int(gc_matrix_set["TileMatrix"][0]["TileWidth"]),- int(gc_matrix_set["TileMatrix"][0]["TileHeight"])- ]- }-- if(type(gc_contents["TileMatrixSet"]) is OrderedDict):- process_matrix_set(gc_contents["TileMatrixSet"])- else:- for gc_matrix_set in gc_contents["TileMatrixSet"]:- process_matrix_set(gc_matrix_set)-- output_file = os.path.join(output_dir, entry["to"])- with open(output_file, "w") as fp:- json.dump(wv, fp, **json_options)- print "%s: %d error(s), %d warning(s), %d layers for %s" % (prog,- error_count, warning_count, layer_count, entry["source"])- return [error_count, warning_count, layer_count]---# Main-colormaps = {}-for entry in entries:- error_count, warning_count, layer_count = process_entry(entry, colormaps)- total_error_count += error_count- total_warning_count += warning_count- total_layer_count += layer_count--print "%s: %d error(s), %d warning(s), %d layers" % (prog, total_error_count,- total_warning_count, total_layer_count)--if total_error_count > 0:- sys.exit(1)diff --git a/tasks/python2.7/getCapabilities.py b/tasks/python2.7/getCapabilities.pydeleted file mode 100755index eb61ff94a..000000000--- a/tasks/python2.7/getCapabilities.py+++ /dev/null@@ -1,200 +0,0 @@-#!/usr/bin/env python--from optparse import OptionParser-from datetime import datetime-from collections import OrderedDict-import os-import sys-import json-import urllib3-import urllib3.contrib.pyopenssl-import xmltodict-import traceback-import certifi--prog = os.path.basename(__file__)-base_dir = os.path.join(os.path.dirname(__file__), "..")-version = "1.0.0"-help_description = """\-Fetches options from remote locations-"""--parser = OptionParser(usage="Usage: %s <config> <output_dir>" % prog,- version="%s version %s" % (prog, version),- epilog=help_description)--(options, args) = parser.parse_args()-if len(args) != 2:- parser.error("Invalid number of arguments")--config_file = args[0]-output_dir = args[1]-colormaps = {}-vectorstyles = {}-vectordata = {}-colormaps_dir = os.path.join(output_dir, "colormaps")-vectorstyles_dir = os.path.join(output_dir, "vectorstyles")-vectordata_dir = os.path.join(output_dir, "vectordata")-remote_count = 0-error_count = 0-warning_count = 0--urllib3.contrib.pyopenssl.inject_into_urllib3()-http = urllib3.PoolManager(- cert_reqs='CERT_REQUIRED',- ca_certs=certifi.where()-)--if not os.path.exists(output_dir):- os.makedirs(output_dir)--with open(config_file) as fp:- config = json.load(fp)--def process_vector_data(layer):- if "ows:Metadata" in layer and layer["ows:Metadata"] is not None:- for item in layer["ows:Metadata"]:- schema_version = item["@xlink:role"]- if schema_version == "http://earthdata.nasa.gov/gibs/metadata-type/layer/1.0":- vector_data_link = item["@xlink:href"]- vector_data_file = os.path.basename(vector_data_link)- vector_data_id = os.path.splitext(vector_data_file)[0]- vectordata[vector_data_id] = vector_data_link--def process_layer(layer):- ident = layer["ows:Identifier"]- if "ows:Metadata" in layer:- if ident in config.get("skipPalettes", []):- sys.stderr.write("%s: WARN: Skipping palette for %s\n" %- prog, ident)- global warning_count- warning_count += 1- elif layer["ows:Metadata"] is not None:- for item in layer["ows:Metadata"]:- schema_version = item["@xlink:role"]- if schema_version == "http://earthdata.nasa.gov/gibs/metadata-type/colormap/1.3":- colormap_link = item["@xlink:href"]- #colormap_link = layer["ows:Metadata"]["@xlink:href"]- colormap_file = os.path.basename(colormap_link)- colormap_id = os.path.splitext(colormap_file)[0]- colormaps[colormap_id] = colormap_link-- elif schema_version == "http://earthdata.nasa.gov/gibs/metadata-type/mapbox-gl-style/1.0":- vector_style_link = item["@xlink:href"]- vector_style_file = os.path.basename(vector_style_link)- vector_style_id = os.path.splitext(vector_style_file)[0]- vectorstyles[vector_style_id] = vector_style_link--def process_remote(entry):- url = entry["from"]- print "%s: %s" % (prog, url)- response = http.request('GET', url)- contents = response.data- output_file = os.path.join(output_dir, entry["to"])-- # Write GetCapabilities responses to XML files- with open(output_file, "w") as fp:- fp.write(contents)- gc = xmltodict.parse(contents)-- # Find all colormaps and vectorstyles in GetCapabilities responses and store them in memory- if gc["Capabilities"]["Contents"] is None:- print('error: %s: no layers' % url)- return-- try:- if(type(gc["Capabilities"]["Contents"]["Layer"]) is OrderedDict):- process_layer(gc["Capabilities"]["Contents"]["Layer"])- process_vector_data(gc["Capabilities"]["Contents"]["Layer"])- else:- for layer in gc["Capabilities"]["Contents"]["Layer"]:- process_layer(layer)- process_vector_data(layer)-- except Exception as e:- print('error: %s: %s' % (url, str(e)))- print(str(traceback.format_exc()))--# Fetch every colormap from the API and write response to file system-def process_colormaps():- print "%s: Fetching %d colormaps" % (prog, len(colormaps))- sys.stdout.flush()- if not os.path.exists(colormaps_dir):- os.makedirs(colormaps_dir)- for link in colormaps.values():- try:- response = http.request("GET", link)- contents = response.data- output_file = os.path.join(colormaps_dir, os.path.basename(link))- with open(output_file, "w") as fp:- fp.write(contents)- except Exception as e:- sys.stderr.write("%s: WARN: Unable to fetch %s: %s\n" %- (prog, link, str(e)))- global warning_count- warning_count += 1--# Fetch every vectorstyle from the API and write response to file system-def process_vectorstyles():- print "%s: Fetching %d vectorstyles" % (prog, len(vectorstyles))- sys.stdout.flush()- if not os.path.exists(vectorstyles_dir):- os.makedirs(vectorstyles_dir)- for link in vectorstyles.values():- try:- response = http.request("GET", link)- contents = response.data- if link.endswith('.json'):- output_file = os.path.join(vectorstyles_dir, os.path.basename(link))- with open(output_file, "w") as fp:- fp.write(contents)- except Exception as e:- sys.stderr.write("%s: WARN: Unable to fetch %s: %s" %- (prog, link, str(e)))- global warning_count- warning_count += 1--# Fetch every vectordata from the API and write response to file system-def process_vectordata():- print "%s: Fetching %d vectordata" % (prog, len(vectordata))- sys.stdout.flush()- if not os.path.exists(vectordata_dir):- os.makedirs(vectordata_dir)- for link in vectordata.values():- try:- response = http.request("GET", link)- contents = response.data- if link.endswith('.json'):- output_file = os.path.join(vectordata_dir, os.path.basename(link))- with open(output_file, "w") as fp:- fp.write(contents)- except Exception as e:- sys.stderr.write("%s: WARN: Unable to fetch %s: %s" %- (prog, link, str(e)))- global warning_count- warning_count += 1--tolerant = config.get("tolerant", False)-if "wv-options-fetch" in config:- for entry in config["wv-options-fetch"]:- try:- remote_count += 1- process_remote(entry)- except Exception as e:- if tolerant:- warning_count += 1- sys.stderr.write("%s: WARN: %s\n" % (prog, str(e)))- else:- error_count += 1- sys.stderr.write("%s: ERROR: %s\n" % (prog, str(e)))- if colormaps:- process_colormaps()- if vectorstyles:- process_vectorstyles()- if vectordata:- process_vectordata()--print "%s: %d error(s), %d remote(s)" % (prog, error_count, remote_count)--if error_count > 0:- sys.exit(1)diff --git a/tasks/python2.7/mergeConfig.py b/tasks/python2.7/mergeConfig.pydeleted file mode 100755index 88d493d1a..000000000--- a/tasks/python2.7/mergeConfig.py+++ /dev/null@@ -1,74 +0,0 @@-#!/usr/bin/env python--from copy import deepcopy-from optparse import OptionParser-import os-import sys-import json--prog = os.path.basename(__file__)-base_dir = os.path.join(os.path.dirname(__file__), "..")-version = "2.0.0"-help_description = """\-Concatenates all configuration items a directory into one configuration file.-"""--# dict_merge from-# http://blog.impressiver.com/post/31434674390/deep-merge-multiple-python-dicts-def dict_merge(target, *args):- # Merge multiple dicts- if len(args) > 1:- for obj in args:- dict_merge(target, obj)- return target-- # Recursively merge dicts and set non-dict values- obj = args[0]- if not isinstance(obj, dict):- return obj- for k, v in obj.iteritems():- if k in target and isinstance(target[k], dict):- dict_merge(target[k], v)- else:- target[k] = deepcopy(v)- return target---# MAIN-parser = OptionParser(usage="Usage: %s <input_dir> <output_file>" % prog,- version="%s version %s" % (prog, version),- epilog=help_description)--(options, args) = parser.parse_args()-if len(args) != 2:- parser.error("Invalid number of arguments")--input_dir = args[0]-output_file = args[1]--conf = {}-file_count = 0-for root, dirs, files in os.walk(input_dir):- dirs.sort()- for file in sorted(files):- try:- if not file.endswith(".json"):- continue- file_count += 1- with open(os.path.join(root, file)) as fp:- data = json.load(fp)- dict_merge(conf, data)- except Exception as e:- sys.stderr.write("ERROR: %s: %s\n" %- (os.path.join(root, file), str(e)))- sys.exit(1)--json_options = {}-json_options["indent"] = 2-json_options["separators"] = (',', ': ')--with open(output_file, "w") as fp:- json.dump(conf, fp, **json_options)--print "%s: %s file(s) merged into %s" % (prog, file_count,- os.path.basename(output_file))diff --git a/tasks/python2.7/processColormap.py b/tasks/python2.7/processColormap.pydeleted file mode 100755index e1a65f3b2..000000000--- a/tasks/python2.7/processColormap.py+++ /dev/null@@ -1,246 +0,0 @@-#!/usr/bin/env python--from optparse import OptionParser-import os-import re-import sys-import json-import xmltodict--prog = os.path.basename(__file__)-base_dir = os.path.join(os.path.dirname(__file__), "..")-version = "3.0.0"-help_description = """\-Converts colormaps to JSON files-"""--parser = OptionParser(usage="Usage: %s <config_file> <input_dir> <output_dir>" % prog,- version="%s version %s" % (prog, version),- epilog=help_description)--(options, args) = parser.parse_args()-if len(args) != 3:- parser.error("Invalid number of arguments")--config_file = args[0]-input_dir = args[1]-output_dir = args[2]--with open(config_file) as fp:- config = json.load(fp)-skips = config.get("skipPalettes", [])--def to_list(v):- return v if isinstance(v, list) else [v]--def match_legend(entry, legends):- try:- matched = "false"- for legend in legends:- if "@id" not in legend:- raise KeyError("No legend IDs")- if legend["@id"] == entry["@ref"]:- matched = legend- return matched- except ValueError as e:- raise ValueError("Invalid reference: %s" % entry["@ref"])--# function returns a max or-# min value from a list-def get_extreme(extreme_list, extreme):- if(extreme == "max"):- if "+INF" in extreme_list:- return 'infinity'- else:- return max(extreme_list)- else:- if "-INF" in extreme_list:- return "neg-infinity"- else:- return min(extreme_list)--# Adds tooltip string to selected-# indexes that need to be replace.-def apply_tooltip(tooltip, tooltip_list, index_list):- for index in index_list:- tooltip_list[index] = tooltip.decode("utf-8") # make unicode- return tooltip_list--# to combines data values of corresponding-# colors-def replace_duplicates(duplicates, tooltip_list, entries):- dup_color_list = list(set(duplicates)) #removes array duplicates- for n, color in enumerate(dup_color_list): # loops through duplicate colors- min_list = []- max_list = []- index_list = []- for index, entry in enumerate(entries):- if(color == entry["@rgb"]):- # get min- value = entry['@value'].encode('ascii','ignore')- value = value.split(',')- if(len(value) > 1):- value[0] = value[0].replace("[", "")- min_list += [value[0]] # adds value to min array- # get max- value[1] = value[1].replace(")", "")- max_list += [value[1]] # adds value to max array- # add index- else:- min_list += [value[0]] # adds value to min array- max_list += [value[0]] # adds value to max array- index_list += [index]- # get max and min values- max_value = get_extreme(max_list, "max")- min_value = get_extreme(min_list, "min")- sep = ' - '- # handle infinity values- if(max_value == "infinity" or min_value == "neg-infinity"):- if(min_value == "neg-infinity"):- tooltip = '< ' + max_value- else:- tooltip = '>= ' + min_value- # zero range delta- elif min_value == max_value:- tooltip = min_value- # two different none-infinity values- # in range- else:- tooltip = min_value + sep + max_value-- tooltip_list = apply_tooltip(tooltip, tooltip_list, index_list)-- return tooltip_list--def process_entries(colormap):- entries = to_list(colormap["Entries"]["ColorMapEntry"])-- transparent_map = "true"- for entry in entries:- if entry["@transparent"] == "false":- transparent_map = "false"- if (transparent_map == "true"):- return "transparent"-- if "Legend" not in colormap:- raise KeyError("No Legend")- else:- map_type = colormap["Legend"]["@type"]- legends = to_list(colormap["Legend"]["LegendEntry"])- colors = []- values = []- tooltips = []- matches = []-- color_format = "{0:02x}{1:02x}{2:02x}{3:02x}"- for index, entry in enumerate(entries):- legend = match_legend(entry, legends)- if (legend == "false"):- continue- r,g,b = entry["@rgb"].split(",")- a = 0 if entry.get("@transparent", "false") == "true" else 255- if a == 0:- continue- colors += [color_format.format(int(r), int(g), int(b), a)]-- if "@tooltip" not in legend:- raise KeyError("No tooltips in legend")- tooltip = legend["@tooltip"]- if (index > 0):- if (entry["@rgb"] == entries[index-1]["@rgb"]):- if (map_type == "continuous") or (map_type == "discrete"):- matches += [entry["@rgb"]]- tooltips += [tooltip]-- if (map_type == "continuous") or (map_type == "discrete"):- items = re.sub(r"[\(\)\[\]]", "", entry["@value"]).split(",")- try:- new_items = []- for item in items:- v = float(item)- if v == float("inf"):- v = sys.float_info.max- if v == float("-inf"):- v = sys.float_info.min- new_items += [v]- values += [new_items]- except ValueError as e:- raise ValueError("Invalid value: %s" % entry["@value"])- if (len(matches) > 0 and len(tooltips) > 0):- tooltips = replace_duplicates(matches, tooltips, entries)-- result = {- "type": map_type,- "entries": {- "type": map_type,- "colors": colors,- },- "legend": {- "tooltips": tooltips,- "colors": colors,- "type": map_type- }- }- if (map_type == "continuous") or (map_type == "discrete"):- result["entries"]["values"] = values-- return result--def process_file(file):- input_file = os.path.join(root, file)- id = os.path.splitext(os.path.basename(input_file))[0]- if id in skips:- sys.stderr.write("%s: WARN: [%s] %s\n" % (prog, input_file,- "Skipping"))- return-- with open(input_file) as fp:- xml = fp.read()- document = xmltodict.parse(xml)- colormaps = to_list(document["ColorMaps"]["ColorMap"])- maps = []- for colormap in colormaps:- result = process_entries(colormap)- if result == "transparent":- continue- result["title"] = colormap["@title"]- result["entries"]["title"] = colormap["@title"]- result["legend"]["title"] = colormap["@title"]- result["legend"]["id"] = id + "_" + str(len(maps)) + "_legend"- if "@minLabel" in colormap["Legend"]:- result["legend"]["minLabel"] = colormap["Legend"]["@minLabel"]- if "@maxLabel" in colormap["Legend"]:- result["legend"]["maxLabel"] = colormap["Legend"]["@maxLabel"]- if "@units" in colormap:- result["legend"]["units"] = colormap["@units"]- maps += [result]-- data = {- "id": id,- "maps": maps- }- json_options = {}- json_options["indent"] = 2- json_options["separators"] = (',', ': ')-- output_file = os.path.join(output_dir, id + ".json")- with open(output_file, "w") as fp:- json.dump(data, fp, **json_options)--# Main-file_count = 0-error_count = 0--for root, dirs, files in os.walk(input_dir):- for file in files:- try:- file_count += 1- process_file(file)- except Exception as e:- sys.stderr.write("%s: ERROR: [%s] %s\n" % (prog, file, str(e)))- error_count += 1--print "%s: %d error(s), %d file(s)" % (prog, error_count, file_count)--if error_count > 0:- sys.exit(1)diff --git a/tasks/python2.7/processTemporalLayer.py b/tasks/python2.7/processTemporalLayer.pydeleted file mode 100755index ca3506bc2..000000000--- a/tasks/python2.7/processTemporalLayer.py+++ /dev/null@@ -1,70 +0,0 @@-from datetime import datetime, date, timedelta-import isodate-import re--def to_list(val):- return [val] if not hasattr(val, 'reverse') else val--# Add duration to end date using-# ISO 8601 duration keys-def determine_end_date(key, date):- return date + isodate.parse_duration(key)--# This method takes a layer and a temporal-# value and tranlates it to start and end dates-def process_temporal(wv_layer, value):- try:- ranges = to_list(value)- if "T" in ranges[0]:- wv_layer["period"] = "subdaily"- else:- if ranges[0].endswith("Y"):- wv_layer["period"] = "yearly"- elif ranges[0].endswith("M"):- wv_layer["period"] = "monthly"- else:- wv_layer["period"] = "daily"- start_date = datetime.max- end_date = datetime.min- date_range_start, date_range_end, range_interval = [], [], []- for range in ranges:- times = range.split('/')- if wv_layer["period"] == "daily" \- or wv_layer["period"] == "monthly" \- or wv_layer["period"] == "yearly":- start_date = min(start_date,- datetime.strptime(times[0], "%Y-%m-%d"))- end_date = max(end_date,- datetime.strptime(times[1], "%Y-%m-%d"))- if start_date:- startDateParse = datetime.strptime(times[0], "%Y-%m-%d")- date_range_start.append(startDateParse.strftime("%Y-%m-%d") + "T" + startDateParse.strftime("%H:%M:%S") + "Z")- if end_date:- endDateParse = datetime.strptime(times[1], "%Y-%m-%d")- date_range_end.append(endDateParse.strftime("%Y-%m-%d") + "T" + endDateParse.strftime("%H:%M:%S") + "Z")- if times[2] != "P1D":- end_date = determine_end_date(times[2], end_date)- range_interval.append(re.search(r'\d+', times[2]).group())- else:- startTime = times[0].replace('T', ' ').replace('Z', '')- endTime = times[1].replace('T', ' ').replace('Z', '')- start_date = min(start_date,- datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S"))- end_date = max(end_date,- datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S"))- if start_date:- startTimeParse = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")- date_range_start.append(startTimeParse.strftime("%Y-%m-%d") + "T" + startTimeParse.strftime("%H:%M:%S") + "Z")- if end_date:- endTimeParse = datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")- date_range_end.append(endTimeParse.strftime("%Y-%m-%d") + "T" + endTimeParse.strftime("%H:%M:%S") + "Z")- range_interval.append(re.search(r'\d+', times[2]).group())- wv_layer["startDate"] = start_date.strftime("%Y-%m-%d") + "T" + start_date.strftime("%H:%M:%S") + "Z"- if end_date != datetime.min:- wv_layer["endDate"] = end_date.strftime("%Y-%m-%d") + "T" + end_date.strftime("%H:%M:%S") + "Z"- if date_range_start and date_range_end:- wv_layer["dateRanges"] = [{"startDate": s, "endDate": e, "dateInterval": i} for s, e, i in zip(date_range_start, date_range_end, range_interval)]- except ValueError:- raise- raise Exception("Invalid time: {0}".format(range))- return wv_layerdiff --git a/tasks/python2.7/processVectorData.py b/tasks/python2.7/processVectorData.pydeleted file mode 100755index 87d5eda44..000000000--- a/tasks/python2.7/processVectorData.py+++ /dev/null@@ -1,63 +0,0 @@-#!/usr/bin/env python--from optparse import OptionParser-import os-import sys-import json-import shutil--prog = os.path.basename(__file__)-base_dir = os.path.join(os.path.dirname(__file__), "..")-version = "3.0.0"-help_description = """\-Converts vector data to JSON files-"""--parser = OptionParser(usage="Usage: %s <config_file> <vectordata_input_dir> <output_dir>" % prog,- version="%s version %s" % (prog, version),- epilog=help_description)--(options, args) = parser.parse_args()-if len(args) != 3:- parser.error("Invalid number of arguments")--config_file = args[0]-vectordata_input_dir = args[1]-output_dir = args[2]--with open(config_file) as fp:- config = json.load(fp)--def copy_file(file):- input_file = os.path.join(root, file)- if input_file.endswith('.json'):- response_data = {}- vector_layer_filename = file;- vector_layer_id = vector_layer_filename.split(".json", 1)[0]- response_data["vectorData"] = {}- response_data["vectorData"][vector_layer_id] = {}- with open(input_file) as json_file:- initial_data = json.load(json_file)- for i in initial_data:- response_data["vectorData"][vector_layer_id][i] = initial_data[i]- with open(input_file, 'w') as json_file:- json.dump(response_data, json_file,indent=2)- shutil.copy(input_file, output_dir)--# Main-file_count = 0-error_count = 0--for root, dirs, files in os.walk(vectordata_input_dir):- for file in files:- try:- file_count += 1- copy_file(file)- except Exception as e:- sys.stderr.write("%s: ERROR: [%s] %s\n" % (prog, file, str(e)))- error_count += 1--print "%s: %d error(s), %d file(s)" % (prog, error_count, file_count)--if error_count > 0:- sys.exit(1)diff --git a/tasks/python2.7/processVectorStyles.py b/tasks/python2.7/processVectorStyles.pydeleted file mode 100755index b8e7fcf4d..000000000--- a/tasks/python2.7/processVectorStyles.py+++ /dev/null@@ -1,63 +0,0 @@-#!/usr/bin/env python--from optparse import OptionParser-import os-import sys-import json-import shutil--prog = os.path.basename(__file__)-base_dir = os.path.join(os.path.dirname(__file__), "..")-version = "3.0.0"-help_description = """\-Converts vector data to JSON files-"""--parser = OptionParser(usage="Usage: %s <config_file> <vectordata_input_dir> <output_dir>" % prog,- version="%s version %s" % (prog, version),- epilog=help_description)--(options, args) = parser.parse_args()-if len(args) != 3:- parser.error("Invalid number of arguments")--config_file = args[0]-vectordata_input_dir = args[1]-output_dir = args[2]--with open(config_file) as fp:- config = json.load(fp)--def copy_file(file):- input_file = os.path.join(root, file)- if input_file.endswith('.json'):- response_data = {}- vector_layer_filename = file;- vector_layer_id = vector_layer_filename.split(".json", 1)[0]- response_data["vectorStyles"] = {}- response_data["vectorStyles"][vector_layer_id] = {}- with open(input_file) as json_file:- initial_data = json.load(json_file)- for i in initial_data:- response_data["vectorStyles"][vector_layer_id][i] = initial_data[i]- with open(input_file, 'w') as json_file:- json.dump(response_data, json_file,indent=2)- shutil.copy(input_file, output_dir)--# Main-file_count = 0-error_count = 0--for root, dirs, files in os.walk(vectordata_input_dir):- for file in files:- try:- file_count += 1- copy_file(file)- except Exception as e:- sys.stderr.write("%s: ERROR: [%s] %s\n" % (prog, file, str(e)))- error_count += 1--print "%s: %d error(s), %d file(s)" % (prog, error_count, file_count)--if error_count > 0:- sys.exit(1)diff --git a/tasks/python2.7/validateOptions.py b/tasks/python2.7/validateOptions.pydeleted file mode 100755index 69bf75f34..000000000--- a/tasks/python2.7/validateOptions.py+++ /dev/null@@ -1,199 +0,0 @@-#!/usr/bin/env python--from datetime import datetime, date, timedelta-import json-from optparse import OptionParser-import os-import sys-import time-from processTemporalLayer import process_temporal--prog = os.path.basename(__file__)-base_dir = os.path.join(os.path.dirname(__file__), "..")-version = "1.0.0"-help_description = """\-Validates and corrects the configuration files.-"""--parser = OptionParser(usage="Usage: %s <config_json> <config_dir>" % prog,- version="%s version %s" % (prog, version),- epilog=help_description)-(options, args) = parser.parse_args()--if len(args) != 2:- parser.error("Invalid number of arguments")--options_file = args[0]-config_dir = args[1]--error_count = 0-warning_count = 0-remove_count = 0--main_config_file = os.path.join(config_dir, "wv.json")-with open(main_config_file) as fp:- wv = json.load(fp)-with open(options_file) as fp:- opt = json.load(fp)--tolerant = opt.get("tolerant", False)--def fail(message):- global error_count- sys.stderr.write("%s: ERROR: %s\n" % (prog, message))- error_count += 1--def error(message):- warn(message) if tolerant else fail(message)--def warn(message):- global warning_count- sys.stderr.write("%s: WARN: %s\n" % (prog, message))- warning_count += 1--def remove_layer(wv, layer_id):- global remove_count- remove_count += 1- del wv["layers"][layer_id]- if layer_id in wv["layerOrder"]: wv["layerOrder"].remove(layer_id)--def isDateTimeFormat(input):- try:- datetime.strptime(input, '%Y-%m-%d %H:%M:%S')- return True- except ValueError:- return False--if tolerant:- warn("Validation enforcement disabled")--start_date = datetime.max--for layer_id in wv["layers"].keys():- layer = wv["layers"][layer_id]- if layer_id != layer["id"]:- error("[%s] layer id does not match id of %s" % (layer_id, layer["id"]))- if layer_id not in wv["layerOrder"]:- if layer_id in opt.get("layerOrderExceptions", []):- remove_layer(wv, layer_id)- continue- elif tolerant or opt.get("ignoreLayerOrder", False):- wv["layerOrder"] += [layer_id]- else:- remove_layer(wv, layer_id)- continue- if "projections" not in layer or len(layer["projections"]) == 0:- error("[%s] No projections defined or not found in GC documents" %- layer_id)- remove_layer(wv, layer_id)- continue- if "type" not in layer:- error("[" + layer_id + "] No type defined. Possible to be expecting " +- "configuration via GC document but was not found")- remove_layer(wv, layer_id)- continue- if "palette" in layer and "id" not in layer["palette"]:- error("[%s] No palette definition" % (layer_id))- elif "palette" in layer:- palette_id = layer["palette"]["id"]- if not os.path.exists(os.path.join(config_dir, "palettes",- palette_id + ".json")):- error("[%s] Unknown palette: %s" % (layer_id, palette_id))- del layer["palette"]- if "vectorStyle" in layer and "id" not in layer["vectorStyle"]:- error("[%s] No vectorStyle definition" % (layer_id))- elif "vectorStyle" in layer:- vector_style_id = layer["vectorStyle"]["id"]- if not os.path.exists(os.path.join(config_dir, "vectorstyles",- vector_style_id + ".json")):- error("[%s] Unknown vector style: %s" % (layer_id, vector_style_id))- del layer["vectorStyle"]- if "group" not in layer and opt.get("warnOnUnexpectedLayer"):- error("[%s] Possible unexpected layer, no group defined" % layer_id)- remove_layer(wv, layer_id)- continue- elif "group" not in layer:- remove_layer(wv, layer_id)- continue- for proj_id in layer["projections"].keys():- projection = layer["projections"][proj_id]- if "matrixSet" in projection:- source = projection["source"]- matrix_set = projection["matrixSet"]- if source not in wv["sources"]:- error("[%s:%s] Invalid source: %s" %- (layer_id, proj_id, source))- del layer["projections"][proj_id]- elif "matrixSets" not in wv["sources"][source]:- error("[%s:%s] No matrix sets for projection" %- (layer_id, proj_id))- del layer["projections"][proj_id]- elif matrix_set not in wv["sources"][source]["matrixSets"]:- error("[%s:%s] Invalid matrix set: %s" %- (layer_id, proj_id, matrix_set))- del layer["projections"][proj_id]- if "temporal" in layer:- warn("[%s] GC Layer temporal values overwritten by Options" % layer_id)- layer = process_temporal(layer, layer["temporal"])- if layer.get("futureTime"):- if "endDate" in layer:- del layer["endDate"]- if layer.get("inactive", False) or layer.get("futureLayer", False):- pass- else:- if "endDate" in layer:- del layer["endDate"]- if "startDate" in layer:- startTime = layer["startDate"].replace('T', ' ').replace('Z', '')- if isDateTimeFormat(startTime):- d = datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S")- else:- d = datetime.strptime(layer["startDate"], "%Y-%m-%d")- start_date = min(start_date, d)--if start_date != datetime.max:- wv["startDate"] = start_date.strftime("%Y-%m-%d") + "T" + start_date.strftime("%H:%M:%S") + "Z";--for layer_id in wv["layerOrder"]:- if layer_id not in wv["layers"]:- error("[%s] In layer order but no definition" % layer_id)--startingLayers = []-for startingLayer in wv["defaults"]["startingLayers"]:- if startingLayer["id"] not in wv["layers"]:- error("Invalid starting layer: %s" % (startingLayer["id"]))- else:- startingLayers += [startingLayer]-wv["defaults"]["startingLayers"] = startingLayers-wv["buildDate"] = int(round(time.time() * 1000))--for projection, projectionValue in wv["naturalEvents"]["layers"].iteritems():- for eventType, eventTypeLayerList in projectionValue.iteritems():- for layerObject in eventTypeLayerList:- if layerObject[0] not in wv["layers"]:- error("The %s layer in the Natural events %s %s config does not have a matching ID in the layer config" %- (layerObject[0], projection, eventType))--for measurement in wv["measurements"].values():- if "sources" not in measurement:- continue- for source in measurement["sources"].values():- if "settings" not in source:- continue- for setting in source["settings"]:- if setting not in wv["layers"]:- error("In measurement %s, source %s, layer not found: %s" %- (measurement["id"], source["id"], setting))--print "%s: %d error(s), %d warning(s), %d removed" % (prog, error_count,- warning_count, remove_count)--json_options = {}-json_options["indent"] = 2-json_options["separators"] = (',', ': ')--with open(main_config_file, "w") as fp:- json.dump(wv, fp)--if error_count > 0:- sys.exit(1)diff --git a/tasks/python3/processVectorData.py b/tasks/python3/processVectorData.pyindex 8bc72a174..07ba42a9d 100755--- a/tasks/python3/processVectorData.py+++ b/tasks/python3/processVectorData.py@@ -33,7 +33,7 @@ def copy_file(file):if input_file.endswith('.json'):response_data = {}vector_layer_filename = file;- vector_layer_id = vector_layer_filename.split(".", 1)[0]+ vector_layer_id = vector_layer_filename.split(".json", 1)[0]response_data["vectorData"] = {}response_data["vectorData"][vector_layer_id] = {}with open(input_file) as json_file:diff --git a/tasks/python3/processVectorStyles.py b/tasks/python3/processVectorStyles.pyindex e71b6b6ad..59dd84020 100755--- a/tasks/python3/processVectorStyles.py+++ b/tasks/python3/processVectorStyles.py@@ -33,7 +33,7 @@ def copy_file(file):if input_file.endswith('.json'):response_data = {}vector_layer_filename = file;- vector_layer_id = vector_layer_filename.split(".", 1)[0]+ vector_layer_id = vector_layer_filename.split(".json", 1)[0]response_data["vectorStyles"] = {}response_data["vectorStyles"][vector_layer_id] = {}with open(input_file) as json_file:diff --git a/tasks/pythonInstall.sh b/tasks/pythonInstall.shindex 67437ee92..4f149d63b 100755--- a/tasks/pythonInstall.sh+++ b/tasks/pythonInstall.sh@@ -2,31 +2,22 @@# Install python dependenciesPYTHON_VERSION="$(python -V 2>&1)"if [ $1 = "linux" ]; then- if [command -v python3 &>/dev/null] || [[ $PYTHON_VERSION = *"Python 3"* ]]; then+ if command -v python3 &>/dev/null || [[ $PYTHON_VERSION = *"Python 3"* ]]; thenecho "Installing virtualenv with python3"python3 -m pip install --user virtualenvpython3 -m virtualenv .pythonPATH=.python/bin:${PATH} pip install -r requirements.txt# If is a linux machine try to run python2- elif command -v python2 &>/dev/null; then- echo "Installing virtualenv with python2"- python2 -m pip install --user virtualenv- python2 -m virtualenv .python- PATH=.python/bin:${PATH} pip install -r requirements-2.7.txtelse- echo "Installing virtualenv with python"- python -m pip install --user virtualenv- python -m virtualenv .python- PATH=.python/bin:${PATH} pip install -r requirements-2.7.txt+ echo "Please install or update python v3"fielse# If is a window machine use virtualenv- if [command -v python3 &>/dev/null] || [[ $PYTHON_VERSION = *"Python 3"* ]]; then+ if command -v python3 &>/dev/null || [[ $PYTHON_VERSION = *"Python 3"* ]]; thenvirtualenv .pythonPATH=.python/Scripts:${PATH} pip install -r requirements.txtelse- virtualenv .python- PATH=.python/Scripts:${PATH} pip install -r requirements-2.7.txt+ echo "Please install or update python v3"fifi