from . import _add_path
from .libs import *
from .PyTranslate import _
import logging
try:
from osgeo import gdal, osr, ogr
gdal.UseExceptions()
ogr.UseExceptions()
osr.UseExceptions()
except ImportError as e:
# print(e)
raise Exception(_('Error importing GDAL library\nPlease ensure GDAL is installed and the Python bindings are available\n\ngdal wheels can be found at https://github.com/cgohlke/geospatial-wheels'))
try:
import pyproj
except ImportError as e:
raise ImportError(_('pyproj is not installed. Please install it to use this function.')) from e
from .apps.version import WolfVersion
from .maps import *
from packaging import version
from pathlib import Path
import logging
import sys
#: Root directory for built-in symbols (SVG assets shipped with the package)
[docs]
SYMBOLS_DIR: Path = Path(__file__).resolve().parent / "symbols"
try:
from OpenGL.GL import *
from OpenGL.GLUT import *
except ImportError as e:
[docs]
msg=_('Error importing OpenGL library')
msg+=_(' Python version : ' + sys.version)
msg+=_(' Please check your version of opengl32.dll -- conflict may exist between different files present on your desktop')
raise Exception(msg)
logging.getLogger().setLevel(logging.INFO) # set the default logging level to INFO, so that it is not too verbose by default, but still shows important messages. Users can change this level as needed
[docs]
def set_logging_level(level):
"""
Set the logging level for the wolfhece package.
Args:
level (str): The logging level to set. Can be one of 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'.
"""
levels = {
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL
}
if level in levels:
logging.getLogger().setLevel(levels[level])
logging.info(f"Logging level set to {level}")
# test the logging level by logging a message at each level
logging.debug("This is a DEBUG message")
logging.info("This is an INFO message")
logging.warning("This is a WARNING message")
logging.error("This is an ERROR message")
logging.critical("This is a CRITICAL message")
else:
raise ValueError(f"Invalid logging level: {level}. Valid levels are: {', '.join(levels.keys())}")
[docs]
def ensure_ntv2grid_exists():
"""
Check if the NTV2 grid file exists in the expected location.
"""
from shutil import copyfile
# print('Version de pyproj :', pyproj.__version__)
files = ['be_ign_bd72lb72_etrs89lb08.tif', 'be_ign_hBG18.tif', 'be_ign_README.txt']
pyproj_datadir = Path(pyproj.datadir.get_data_dir())
os.environ["PROJ_DATA"] = pyproj.datadir.get_data_dir() # set the PROJ_DATA environment variable to pyproj data directory
for file in files:
if not (pyproj_datadir / file).exists():
# copy the NTV2 grid file to the pyproj data directory
ntv2_grid_path = Path(__file__).parent / 'lb7208_ntv2' / file
copyfile(ntv2_grid_path, pyproj_datadir / file)
print(f"Copied {file} to {pyproj_datadir}")
__version__ = WolfVersion().get_version()
ensure_ntv2grid_exists()
[docs]
def is_enough(min_version: str) -> bool:
"""
Compare the current version of WolfHece to a given version string.
Args:
version (str): The version string to compare against.
Returns:
bool: True if the current version is greater than or equal to the given version, False otherwise.
"""
return version.Version(__version__) >= version.Version(min_version)
[docs]
def is_opengl_context_available() -> bool:
""" Check if an OpenGL context is defined and available for use """
try:
glGetString(GL_VERSION)
return True
except Exception as e:
logging.debug('OpenGL context not available: {}'.format(e))
return False
[docs]
def _check_version(min_version: str) -> bool:
"""
Check if the current version is greater than or equal to the minimum version.
Args:
min_version (str): The minimum required version.
current_version (str): The current version to check against.
Returns:
bool: True if the current version is greater than or equal to the minimum version, False otherwise.
"""
return version.parse(__version__) >= version.parse(min_version)
[docs]
def check_available_version_on_pypi() -> str:
"""
Check the latest available version of the package on PyPI.
Returns:
str: The latest version available on PyPI.
"""
import requests
from packaging import version
url = "https://pypi.org/pypi/wolfhece/json"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
latest_version = data['info']['version']
return latest_version
else:
raise Exception(f"Failed to fetch version information from PyPI. Status code: {response.status_code}")
[docs]
def can_upgrade_wolfhece() -> bool:
"""
Check if the current version can be upgraded to the minimum required version.
Args:
min_version (str): The minimum required version.
Returns:
bool: True if the current version can be upgraded, False otherwise.
"""
latest_version = check_available_version_on_pypi()
return version.parse(latest_version) >= version.parse(__version__)
[docs]
def check_version(min_version: str) -> bool:
"""
Check if the current version is greater than or equal to the minimum version.
Args:
min_version (str): The minimum required version.
Returns:
bool: True if the current version is greater than or equal to the minimum version, False otherwise.
"""
try:
# Permet de tester la version accessible via le PATH
if _check_version(min_version):
logging.info(f"Version de wolfhece : {min_version} ou supérieure est installée.")
else:
logging.error(f"Version de wolfhece : {min_version} ou supérieure n'est pas installée.")
logging.info(f"Version available on Pypi {check_available_version_on_pypi()}")
logging.info(f"Can I upgrade? {can_upgrade_wolfhece()}")
raise ImportError("Version de wolfhece insuffisante.")
except:
logging.error(f"Erreur lors de la vérification de la version de wolfhece. Assurez-vous que wolfhece est installé et accessible dans le PATH.")
logging.info(f"Version available on Pypi {check_available_version_on_pypi()}")
raise ImportError("Erreur lors de la vérification de la version de wolfhece.")
# Lazy-loaded names (see __getattr__ below):
# UNITS - pint.UnitRegistry, only needed by mockup_spw_xlsx
# PieZonesAsset \
# PieZonesController \
# PieDistributionModel - from .assets.pie (heavy chain: pyvertexvectors → pint → dask)
# build_pie_zones /
# build_pie_controller/
[docs]
_PIE_NAMES = frozenset({
'PieZonesAsset', 'PieZonesController', 'PieDistributionModel',
'build_pie_zones', 'build_pie_controller',
})
def __getattr__(name):
if name == 'UNITS':
import pint
_UNITS = pint.UnitRegistry()
globals()['UNITS'] = _UNITS
return _UNITS
if name in _PIE_NAMES:
from .assets.pie import (
PieZonesAsset,
PieZonesController,
PieDistributionModel,
build_pie_zones,
build_pie_controller,
)
globals().update({
'PieZonesAsset': PieZonesAsset,
'PieZonesController': PieZonesController,
'PieDistributionModel': PieDistributionModel,
'build_pie_zones': build_pie_zones,
'build_pie_controller': build_pie_controller,
})
return globals()[name]
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")