0
  Z   ˆl–Ðz¾” ”Ê:”Ê�jã/\ªbÑ¿�þDóì¾³r…§ŠáBšóÑ„ŽÐ_ŠI|¥�+Wé3ž¯a–Ðz¾”d
i?u8 ™¸Ûwâ˜´oÐ ?÷     #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ******************************************************************************
#  $Id$
#
# Project:  Google Summer of Code 2007, 2008 (http://code.google.com/soc/)
# Support:  BRGM (http://www.brgm.fr)
# Purpose:  Convert a raster into TMS (Tile Map Service) tiles in a directory.
#           - generate Google Earth metadata (KML SuperOverlay)
#           - generate simple HTML viewer based on Google Maps and OpenLayers
#           - support of global tiles (Spherical Mercator) for compatibility
#               with interactive web maps a la Google Maps
# Author:   Klokan Petr Pridal, klokan at klokan dot cz
#
###############################################################################
# Copyright (c) 2008, Klokan Petr Pridal
# Copyright (c) 2010-2013, Even Rouault <even dot rouault at spatialys.com>
# Copyright (c) 2021, Idan Miara <idan@miara.com>
#
#  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.
# ******************************************************************************

from __future__ import division, print_function

import contextlib
import glob
import json
import math
import optparse
import os
import shutil
import stat
import sys
import tempfile
import threading
from functools import partial
from typing import Any, List, NoReturn, Optional, Tuple
from uuid import uuid4
from xml.etree import ElementTree

from osgeo import gdal, osr

Options = Any

try:
    import numpy
    from PIL import Image

    import osgeo.gdal_array as gdalarray

    numpy_available = True
except ImportError:
    # 'antialias' resampling is not available
    numpy_available = False

__version__ = "$Id$"

resampling_list = (
    "average",
    "near",
    "bilinear",
    "cubic",
    "cubicspline",
    "lanczos",
    "antialias",
    "mode",
    "max",
    "min",
    "med",
    "q1",
    "q3",
)
webviewer_list = ("all", "google", "openlayers", "leaflet", "mapml", "none")


def makedirs(path):
    """Wrapper for os.makedirs() that can work with /vsi files too"""
    if path.startswith("/vsi"):
        if gdal.MkdirRecursive(path, 0o755) != 0:
            raise Exception(f"Cannot create {path}")
    else:
        os.makedirs(path, exist_ok=True)


def isfile(path):
    """Wrapper for os.path.isfile() that can work with /vsi files too"""
    if path.startswith("/vsi"):
        stat_res = gdal.VSIStatL(path)
        if stat is None:
            return False
        return stat.S_ISREG(stat_res.mode)
    else:
        return os.path.isfile(path)


class VSIFile:
    """Expose a simplistic file-like API for a /vsi file"""

    def __init__(self, filename, f):
        self.filename = filename
        self.f = f

    def write(self, content):
        if gdal.VSIFWriteL(content, 1, len(content), self.f) != len(content):
            raise Exception("Error while writing into %s" % self.filename)


@contextlib.contextmanager
def my_open(filename, mode):
    """Wrapper for open() built-in m