pyCreateTh update

This commit is contained in:
Alex38Lyon committed 2026-11-19 18:51:48 +01:00
1 parent f900462feb
commit 98fb6dc75e
10 files changed
+2164 -2660

No files matched your search

+73 -2
View File
@@ -1,5 +1,6 @@
{ {
"cSpell.words": [ "cSpell.words": [
"altc",
"annee", "annee",
"ansi", "ansi",
"ARSIP", "ARSIP",
@@ -10,21 +11,37 @@
"Backsights", "Backsights",
"beijing", "beijing",
"buildparam", "buildparam",
"buildthconfig",
"Carth",
"carthesian",
"cavename", "cavename",
"centerlines", "centerlines",
"centi",
"checkfiles",
"clarke", "clarke",
"clino", "clino",
"CLINO", "CLINO",
"colwidth", "colwidth",
"Commecial",
"containging", "containging",
"coordsyst", "coordsyst",
"cumcount", "cumcount",
"Cylp",
"cylpolar",
"datal",
"dataold", "dataold",
"datat", "datat",
"datathwritetools", "datathwritetools",
"Deca",
"décommenter",
"Degd",
"deniv",
"Deniv",
"depmatch", "depmatch",
"depthchange", "depthchange",
"depthre", "depthre",
"dictcave",
"dictl",
"downcasting", "downcasting",
"drawnexemptextendedre", "drawnexemptextendedre",
"drawnexemptplanre", "drawnexemptplanre",
@@ -32,9 +49,11 @@
"drawnre", "drawnre",
"ecart", "ecart",
"ecarts", "ecarts",
"elems",
"ENDC", "ENDC",
"endcenterline", "endcenterline",
"endlayout", "endlayout",
"endmap",
"endscrap", "endscrap",
"endsurvey", "endsurvey",
"equats", "equats",
@@ -45,53 +64,105 @@
"explo", "explo",
"fnme", "fnme",
"formated", "formated",
"fromcount",
"FURB",
"geocentricdatumofaustralia", "geocentricdatumofaustralia",
"geocentricofaustralia", "geocentricofaustralia",
"Geophysicaya", "Geophysicaya",
"github",
"hskip",
"icomments", "icomments",
"icoupe", "icoupe",
"iline",
"isin", "isin",
"istructure", "istructure",
"ithc",
"ithconfig",
"Koef", "Koef",
"Larra", "Larra",
"latc",
"lengthre", "lengthre",
"lenmatch", "lenmatch",
"lensurv",
"levelname", "levelname",
"levelno", "levelno",
"linex", "linex",
"longc",
"LRUD", "LRUD",
"lruddir",
"migovec", "migovec",
"mkfle",
"NODRAW", "NODRAW",
"Noeuds", "Noeuds",
"northamerican", "northamerican",
"northamericandatum", "northamericandatum",
"nostring",
"nosurvey",
"nouvelletriangulationfrançaise", "nouvelletriangulationfrançaise",
"pdfs",
"pulkovo", "pulkovo",
"pytro", "pytro",
"resultats", "resultats",
"roth", "roth",
"rsuffix", "rsuffix",
"scompass",
"sinfo", "sinfo",
"sirgas", "sirgas",
"slopesurv",
"smeters",
"sourcefiles",
"southamerican", "southamerican",
"southamericandatum", "southamericandatum",
"syscoord", "syscoord",
"tendcenterline", "tendcenterline",
"tendcode",
"thanksto", "thanksto",
"Thbook",
"thcfnme",
"thconfig", "thconfig",
"thconfigfnme",
"thcoords",
"thcpath",
"therion", "therion",
"thjunk",
"thlang", "thlang",
"thlocation",
"thmaps",
"thsizel",
"thsizem",
"thsizexl",
"thtot",
"tocount",
"Topof",
"topofil", "topofil",
"totdata", "totdata",
"totfile", "totfile",
"triees", "triees",
"trox", "trox",
"typelem",
"typelen",
"typem",
"unitclino",
"unitcounter",
"Urruty", "Urruty",
"UUUUDDDDSSSB", "UUUUDDDDSSSB",
"UUUUDDDDSSSBL", "UUUUDDDDSSSBL",
"UUUUDDDDSSSSSBL", "UUUUDDDDSSSSSBL",
"versionfle",
"Visualtopo", "Visualtopo",
"vtopo",
"vtopotools",
"Vulc",
"wpage", "wpage",
"XTHERION" "writecenterlineheader",
"writedata",
"writethc",
"writethconfig",
"xavier",
"xcoord",
"XTHERION",
"xvigrid",
"xviscale",
"ycoord"
] ]
} }
+216 -228
View File
@@ -2,12 +2,13 @@
!############################################################################################# !#############################################################################################
# # # #
# general_fonctions.py for pyCreateTh.py # # general_fonctions.py for pyCreateTh.py #
# # # #
!############################################################################################# !#############################################################################################
Alex 2025 06 09 Alex 2025 06 09
""" """
import os, logging, sys, re, configparser, unicodedata, shutil
import os, logging, sys, re, configparser, unicodedata, shutil # noqa: I001
from pathlib import Path from pathlib import Path
import Lib.global_data as global_Data import Lib.global_data as global_Data
from datetime import datetime from datetime import datetime
@@ -21,36 +22,38 @@ log = logging.getLogger("Logger")
# Couleurs ANSI par niveau de log # Couleurs ANSI par niveau de log
################################################################################################# #################################################################################################
COLOR_CODES = { COLOR_CODES = {
logging.DEBUG: "\033[94m", # Bleu logging.DEBUG: "\033[94m", # Bleu
logging.INFO: "\033[92m", # Vert logging.INFO: "\033[92m", # Vert
logging.WARNING: "\033[95m", # MAGENTA logging.WARNING: "\033[95m", # MAGENTA
logging.ERROR: "\033[91m", # Rouge logging.ERROR: "\033[91m", # Rouge
logging.CRITICAL: "\033[1;91m", # Rouge vif logging.CRITICAL: "\033[1;91m", # Rouge vif
} }
RESET = "\033[0m" RESET = "\033[0m"
################################################################################################# #################################################################################################
# Codes de couleur ANSI # Codes de couleur ANSI
class Colors: class Colors:
BLACK = '\033[90m' BLACK = "\033[90m"
RED = '\033[91m' RED = "\033[91m"
GREEN = '\033[92m' GREEN = "\033[92m"
YELLOW = '\033[93m' YELLOW = "\033[93m"
BLUE = '\033[94m' BLUE = "\033[94m"
MAGENTA = '\033[95m' MAGENTA = "\033[95m"
CYAN = '\033[96m' CYAN = "\033[96m"
WHITE = '\033[97m' WHITE = "\033[97m"
ERROR = '\033[91m' ERROR = "\033[91m"
WARNING = '\033[95m' WARNING = "\033[95m"
HEADER = '\033[96m' HEADER = "\033[96m"
DEBUG = '\033[94m' # Bleu DEBUG = "\033[94m" # Bleu
INFO = '\033[92m' # Vert INFO = "\033[92m" # Vert
CRITICAL = '\033[1;91m', # Rouge vif CRITICAL = ("\033[1;91m",) # Rouge vif
ENDC = '\033[0m' ENDC = "\033[0m"
BOLD = '\033[1m' BOLD = "\033[1m"
UNDERLINE = '\033[4m' UNDERLINE = "\033[4m"
################################################################################################# #################################################################################################
# fonction pour réduire l'affichage des chemins long # # fonction pour réduire l'affichage des chemins long #
@@ -68,12 +71,12 @@ def safe_relpath(path, base_dir=None, max_depth=4, max_name_len=50, prefix="~"):
# ── 1. Résolution du chemin ────────────────────────────────────────────── # ── 1. Résolution du chemin ──────────────────────────────────────────────
try: try:
path = Path(path).expanduser().resolve() path = Path(path).expanduser().resolve()
except Exception: except Exception: # noqa: BLE001
return str(path) return str(path)
try: try:
base = Path(base_dir).expanduser().resolve() if base_dir else Path.cwd().resolve() base = Path(base_dir).expanduser().resolve() if base_dir else Path.cwd().resolve()
except Exception: except Exception: # noqa: BLE001
base = None base = None
# ── 2. Nom du fichier / dossier (tronqué) ───────────────────────────────── # ── 2. Nom du fichier / dossier (tronqué) ─────────────────────────────────
@@ -89,7 +92,7 @@ def safe_relpath(path, base_dir=None, max_depth=4, max_name_len=50, prefix="~"):
parts = list(rel.parts) parts = list(rel.parts)
else: else:
raise ValueError raise ValueError
except Exception: except Exception: # noqa: BLE001
parts = list(path.parts) parts = list(path.parts)
# ── 4. Cas path == base → "." ──────────────────────────────────────────── # ── 4. Cas path == base → "." ────────────────────────────────────────────
@@ -108,11 +111,10 @@ def safe_relpath(path, base_dir=None, max_depth=4, max_name_len=50, prefix="~"):
# ── 7. Construction finale sûre ────────────────────────────────────────── # ── 7. Construction finale sûre ──────────────────────────────────────────
try: try:
return os.path.join(*parts) return os.path.join(*parts)
except Exception: except Exception: # noqa: BLE001
return name return name
################################################################################################# #################################################################################################
# Coloration des messages d'aide d'arg # # Coloration des messages d'aide d'arg #
################################################################################################# #################################################################################################
@@ -124,27 +126,27 @@ def colored_help(parser):
parser (argparse.ArgumentParser): Le parseur d'arguments. parser (argparse.ArgumentParser): Le parseur d'arguments.
Returns: Returns:
None None
""" """
# Captures the help output # Captures the help output
help_text = parser.format_help() help_text = parser.format_help()
# Coloration des différentes parties # Coloration des différentes parties
colored_help_text = help_text.replace( colored_help_text = (
'usage:', f'{Colors.ERROR}usage:{Colors.ENDC}' help_text.replace("usage:", f"{Colors.ERROR}usage:{Colors.ENDC}")
).replace( .replace("options:", f"{Colors.GREEN}options:{Colors.ENDC}")
'options:', f'{Colors.GREEN}options:{Colors.ENDC}' .replace("positional arguments:", f"{Colors.BLUE}positional arguments:{Colors.ENDC}")
).replace('positional arguments:', f'{Colors.BLUE}positional arguments:{Colors.ENDC}' .replace(", --help", f"{Colors.BLUE}, --help:{Colors.ENDC}")
).replace(', --help', f'{Colors.BLUE}, --help:{Colors.ENDC}' .replace("elp:", f"{Colors.BLUE}elp{Colors.ENDC}")
).replace('elp:', f'{Colors.BLUE}elp{Colors.ENDC}') )
# Surligner les arguments # Surligner les arguments
for action in parser._actions: for action in parser._actions:
if action.option_strings: if action.option_strings:
# Colorer les options (--xyz) # Colorer les options (--xyz)
for opt in action.option_strings: for opt in action.option_strings:
colored_help_text = colored_help_text.replace(opt, f'{Colors.BLUE}{opt}{Colors.ENDC}').replace('--help', f'{Colors.BLUE}--help:{Colors.ENDC}') colored_help_text = colored_help_text.replace(opt, f"{Colors.BLUE}{opt}{Colors.ENDC}").replace("--help", f"{Colors.BLUE}--help:{Colors.ENDC}")
# Imprimer le texte coloré # Imprimer le texte coloré
print(colored_help_text) print(colored_help_text)
sys.exit(1) sys.exit(1)
@@ -164,25 +166,25 @@ def sanitize_filename(thName):
Returns: Returns:
str: The cleaned and compatible string. str: The cleaned and compatible string.
""" """
# Unicode normalization to replace accented characters with their non-accented equivalents # Unicode normalization to replace accented characters with their non-accented equivalents
thName = unicodedata.normalize('NFKD', thName).encode('ASCII', 'ignore').decode('ASCII') thName = unicodedata.normalize("NFKD", thName).encode("ASCII", "ignore").decode("ASCII")
# Replace parentheses with underscores # Replace parentheses with underscores
thName = thName.replace('(', '_').replace(')', '_') thName = thName.replace("(", "_").replace(")", "_")
# Replace illegal characters with an underscore # Replace illegal characters with an underscore
thName = re.sub(r'[<>:"/\\|?*\']', '_', thName) # Illegal on Windows thName = re.sub(r'[<>:"/\\|?*\']', "_", thName) # Illegal on Windows
thName = re.sub(r'\s+', '_', thName) # Spaces to underscores thName = re.sub(r"\s+", "_", thName) # Spaces to underscores
thName = re.sub(r'[^a-zA-Z0-9._-]', '_', thName) # Keep only allowed chars thName = re.sub(r"[^a-zA-Z0-9._-]", "_", thName) # Keep only allowed chars
# Convert to lowercase, then capitalize the first letter # Convert to lowercase, then capitalize the first letter
# thName = thName.lower().capitalize() # thName = thName.lower().capitalize()
# thName = thName.capitalize() # thName = thName.capitalize()
# Suppression des underscores en début et fin # Suppression des underscores en début et fin
thName = thName.strip('_') thName = thName.strip("_")
return thName or "default_filename" # Avoid empty result return thName or "default_filename" # Avoid empty result
@@ -197,24 +199,24 @@ def select_file_tk_window():
""" """
# Créer une instance de la fenêtre tkinter # Créer une instance de la fenêtre tkinter
root = tk.Tk() root = tk.Tk()
# Cacher la fenêtre principale # Cacher la fenêtre principale
root.withdraw() root.withdraw()
# Afficher la boite de dialogue de sélection de fichier # Afficher la boite de dialogue de sélection de fichier
file_path = filedialog.askopenfilename( file_path = filedialog.askopenfilename(
title="Select your file", title="Select your file",
filetypes=[ filetypes=[
("Compatibles files", "*.th *.mak *.dat *.tro *.trox"), ("Compatibles files", "*.th *.mak *.dat *.tro *.trox"),
("MAK files", "*.mak"), ("MAK files", "*.mak"),
("TH files", "*.th"), ("TH files", "*.th"),
("DAT files", "*.dat"), ("DAT files", "*.dat"),
("TRO files", "*.tro"), ("TRO files", "*.tro"),
("TROX files", "*.trox"), ("TROX files", "*.trox"),
("All files", "*.*")] ("All files", "*.*"),
) ],
)
return file_path # Retourner le chemin complet du fichier sélectionné return file_path # Retourner le chemin complet du fichier sélectionné
@@ -237,58 +239,53 @@ def load_config_old(args, configIni="config.ini"):
config.read(config_file, encoding="utf-8") config.read(config_file, encoding="utf-8")
survey_keys = { survey_keys = {
'Author': 'Author', "Author": "Author",
'Copyright1': 'Copyright', "Copyright1": "Copyright",
'Copyright2': 'Copyright', "Copyright2": "Copyright",
'Copyright3': 'Copyright', "Copyright3": "Copyright",
'Copyright_Short': None, "Copyright_Short": None,
'map_comment': 'mapComment', "map_comment": "mapComment",
'club': 'club', "club": "club",
'thanksto': 'thanksto', "thanksto": "thanksto",
'datat': 'datat', "datat": "datat",
'wpage': 'wpage', "wpage": "wpage",
'cs': 'cs' "cs": "cs",
} }
for key, attr in survey_keys.items(): for key, attr in survey_keys.items():
if 'Survey_Data' in config and key in config['Survey_Data']: if "Survey_Data" in config and key in config["Survey_Data"]:
if key.startswith('Copyright') and all( if key.startswith("Copyright") and all(k in config["Survey_Data"] for k in ["Copyright1", "Copyright2", "Copyright3"]):
k in config['Survey_Data'] for k in ['Copyright1', 'Copyright2', 'Copyright3'] global_Data.Copyright = "\n".join([config["Survey_Data"]["Copyright1"], config["Survey_Data"]["Copyright2"], config["Survey_Data"]["Copyright3"]])
): global_Data.CopyrightShort = config["Survey_Data"]["Copyright_Short"]
global_Data.Copyright = "\n".join([
config['Survey_Data']['Copyright1'],
config['Survey_Data']['Copyright2'],
config['Survey_Data']['Copyright3']
])
global_Data.CopyrightShort = config['Survey_Data']['Copyright_Short']
elif attr: elif attr:
setattr(global_Data, attr, config['Survey_Data'][key]) setattr(global_Data, attr, config["Survey_Data"][key])
app_keys = { app_keys = {
'template_path': 'templatePath', "template_path": "templatePath",
'station_by_scrap': ('stationByScrap', int), "station_by_scrap": ("stationByScrap", int),
'final_therion_exe': ('finalTherionExe', lambda x: x.lower() == 'true'), "final_therion_exe": ("finalTherionExe", lambda x: x.lower() == "true"),
'parse_tro_files_by_explo': ('parse_tro_files_by_explo', lambda x: x.lower() == 'true'), "parse_tro_files_by_explo": ("parse_tro_files_by_explo", lambda x: x.lower() == "true"),
'therion_path': 'therionPath', "therion_path": "therionPath",
'survey_prefix_name': 'SurveyPrefixName', "survey_prefix_name": "SurveyPrefixName",
'shot_lines_in_th2_files': ('linesInTh2', lambda x: x.lower() == 'true'), "shot_lines_in_th2_files": ("linesInTh2", lambda x: x.lower() == "true"),
'station_name_in_th2_files': ('stationNamesInTh2', lambda x: x.lower() == 'true'), "station_name_in_th2_files": ("stationNamesInTh2", lambda x: x.lower() == "true"),
'wall_lines_in_th2_files': ('wallLinesInTh2', lambda x: x.lower() == 'true'), "wall_lines_in_th2_files": ("wallLinesInTh2", lambda x: x.lower() == "true"),
'kSmooth': ('kSmooth', float) "kSmooth": ("kSmooth", float),
} }
for key, value in app_keys.items(): for key, value in app_keys.items():
if 'Application_Data' in config and key in config['Application_Data']: if "Application_Data" in config and key in config["Application_Data"]:
attr, caster = (value, str) if isinstance(value, str) else value attr, caster = (value, str) if isinstance(value, str) else value
setattr(global_Data, attr, caster(config['Application_Data'][key])) setattr(global_Data, attr, caster(config["Application_Data"][key]))
return config_file return config_file
except Exception as e: except Exception as e: # noqa: BLE001
log.critical(f"Reading {configIni} file error: {Colors.ENDC}{e}") log.critical(f"Reading {configIni} file error: {Colors.ENDC}{e}")
exit(0) sys.exit(0)
#################################################################################################
def load_config(args, configIni="config.ini", profile="Default"): def load_config(args, configIni="config.ini", profile="Default"):
""" """
Charge un fichier de configuration .ini et initialise les variables globales. Charge un fichier de configuration .ini et initialise les variables globales.
@@ -300,7 +297,6 @@ def load_config(args, configIni="config.ini", profile="Default"):
Exemple : Survey_Data:PSM Exemple : Survey_Data:PSM
""" """
try: try:
# Chemin potentiel du fichier config # Chemin potentiel du fichier config
config_file = os.path.join(os.path.dirname(args.file), configIni) config_file = os.path.join(os.path.dirname(args.file), configIni)
if not os.path.isfile(config_file): if not os.path.isfile(config_file):
@@ -333,51 +329,39 @@ def load_config(args, configIni="config.ini", profile="Default"):
# ---------------------------------------------------------- # ----------------------------------------------------------
survey_keys = { survey_keys = {
'Author': 'Author', "Author": "Author",
'Copyright1': 'Copyright', "Copyright1": "Copyright",
'Copyright2': 'Copyright', "Copyright2": "Copyright",
'Copyright3': 'Copyright', "Copyright3": "Copyright",
'Copyright_Short': None, "Copyright_Short": None,
'map_comment': 'mapComment', "map_comment": "mapComment",
'club': 'club', "club": "club",
'thanksto': 'thanksto', "thanksto": "thanksto",
'datat': 'datat', "datat": "datat",
'wpage': 'wpage', "wpage": "wpage",
'cs': 'cs' "cs": "cs",
} }
# ========================================================== # ==========================================================
# Variables de substitution # Variables de substitution
# ========================================================== # ==========================================================
variables = { variables = {"YEAR": str(datetime.now().year)} # noqa: DTZ005
"YEAR": str(datetime.now().year)
}
def expand(value): def expand(value):
try: try:
return value.format(**variables) return value.format(**variables)
except Exception: except Exception: # noqa: BLE001
return value return value
# ========================================================== # ==========================================================
# Lecture Survey_Data # Lecture Survey_Data
# ========================================================== # ==========================================================
survey_keys = { survey_keys = {"Author": "Author", "map_comment": "mapComment", "club": "club", "thanksto": "thanksto", "datat": "datat", "wpage": "wpage", "cs": "cs"}
'Author': 'Author',
'map_comment': 'mapComment',
'club': 'club',
'thanksto': 'thanksto',
'datat': 'datat',
'wpage': 'wpage',
'cs': 'cs'
}
for key, attr in survey_keys.items(): for key, attr in survey_keys.items():
if key in survey_cfg: if key in survey_cfg:
value = expand(survey_cfg[key]) value = expand(survey_cfg[key])
setattr(global_Data, attr, value) setattr(global_Data, attr, value)
@@ -389,75 +373,56 @@ def load_config(args, configIni="config.ini", profile="Default"):
copyright_lines = [] copyright_lines = []
for key in ("Copyright1", "Copyright2", "Copyright3"): for key in ("Copyright1", "Copyright2", "Copyright3"):
if key in survey_cfg: if key in survey_cfg:
copyright_lines.append(expand(survey_cfg[key]))
copyright_lines.append(
expand(survey_cfg[key])
)
if copyright_lines: if copyright_lines:
global_Data.Copyright = "\n".join(copyright_lines)
global_Data.Copyright = "\n".join(
copyright_lines
)
if "Copyright_Short" in survey_cfg: if "Copyright_Short" in survey_cfg:
global_Data.CopyrightShort = expand(survey_cfg["Copyright_Short"])
global_Data.CopyrightShort = expand(
survey_cfg["Copyright_Short"]
)
# ---------------------------------------------------------- # ----------------------------------------------------------
# Lecture Application_Data # Lecture Application_Data
# ---------------------------------------------------------- # ----------------------------------------------------------
app_keys = { app_keys = {
'template_path': 'templatePath', "template_path": "templatePath",
'station_by_scrap': ('stationByScrap', int), "station_by_scrap": ("stationByScrap", int),
'final_therion_exe': ('finalTherionExe', lambda x: x.lower() == 'true'), "final_therion_exe": ("finalTherionExe", lambda x: x.lower() == "true"),
'parse_tro_files_by_explo': ('parse_tro_files_by_explo', lambda x: x.lower() == 'true'), "parse_tro_files_by_explo": ("parse_tro_files_by_explo", lambda x: x.lower() == "true"),
'therion_path': 'therionPath', "therion_path": "therionPath",
'survey_prefix_name': 'SurveyPrefixName', "survey_prefix_name": "SurveyPrefixName",
'shot_lines_in_th2_files': ('linesInTh2', lambda x: x.lower() == 'true'), "shot_lines_in_th2_files": ("linesInTh2", lambda x: x.lower() == "true"),
'station_name_in_th2_files': ('stationNamesInTh2', lambda x: x.lower() == 'true'), "station_name_in_th2_files": ("stationNamesInTh2", lambda x: x.lower() == "true"),
'wall_lines_in_th2_files': ('wallLinesInTh2', lambda x: x.lower() == 'true'), "wall_lines_in_th2_files": ("wallLinesInTh2", lambda x: x.lower() == "true"),
'kSmooth': ('kSmooth', float) "kSmooth": ("kSmooth", float),
} }
if 'Application_Data' in config: if "Application_Data" in config:
for key, value in app_keys.items(): for key, value in app_keys.items():
if key not in config['Application_Data']: if key not in config["Application_Data"]:
continue continue
attr, caster = ( attr, caster = (value, str) if isinstance(value, str) else value
(value, str)
if isinstance(value, str)
else value
)
setattr( setattr(global_Data, attr, caster(config["Application_Data"][key]))
global_Data,
attr,
caster(config['Application_Data'][key])
)
# log.info(f"Configuration profile : {profile}") # log.info(f"Configuration profile : {profile}")
return config_file, profile return config_file, profile
except Exception as e: except Exception as e: # noqa: BLE001
log.critical(f"Reading config file : {Colors.ENDC}{configIni}{Colors.ERROR} error : {Colors.ENDC}{e}" ) log.critical(f"Reading config file : {Colors.ENDC}{configIni}{Colors.ERROR} error : {Colors.ENDC}{e}")
exit(0) sys.exit(0)
################################################################################################# #################################################################################################
# Supprime les codes ANSI (pour l'écriture dans les fichiers) # Supprime les codes ANSI (pour l'écriture dans les fichiers)
################################################################################################# #################################################################################################
def strip_ansi_codes(text): def strip_ansi_codes(text):
ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
return ansi_escape.sub('', text) return ansi_escape.sub("", text)
################################################################################################# #################################################################################################
@@ -486,11 +451,11 @@ class FileFormatter(logging.Formatter):
args=(), args=(),
exc_info=record.exc_info, exc_info=record.exc_info,
func=record.funcName, func=record.funcName,
sinfo=record.stack_info sinfo=record.stack_info,
) )
return super().format(record_copy) return super().format(record_copy)
################################################################################################# #################################################################################################
# Fonction de configuration du logger # Fonction de configuration du logger
################################################################################################# #################################################################################################
@@ -498,9 +463,9 @@ def setup_logger(logfile="app.log", debug_log=False):
logger = logging.getLogger("Logger") logger = logging.getLogger("Logger")
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)
logger.handlers.clear() logger.handlers.clear()
min_level = logging.DEBUG if debug_log else logging.INFO min_level = logging.DEBUG if debug_log else logging.INFO
# Console stderr handler — affichage à l'écran avec couleurs # Console stderr handler — affichage à l'écran avec couleurs
stderr_handler = logging.StreamHandler(sys.stderr) stderr_handler = logging.StreamHandler(sys.stderr)
stderr_handler.setLevel(min_level) stderr_handler.setLevel(min_level)
@@ -514,7 +479,7 @@ def setup_logger(logfile="app.log", debug_log=False):
file_formatter = FileFormatter("%(asctime)s - %(levelname)s - %(message)s") # <-- Ta classe personnalisée file_formatter = FileFormatter("%(asctime)s - %(levelname)s - %(message)s") # <-- Ta classe personnalisée
file_handler.setFormatter(file_formatter) file_handler.setFormatter(file_formatter)
logger.addHandler(file_handler) logger.addHandler(file_handler)
return logger return logger
@@ -533,103 +498,105 @@ def copy_template_if_not_exists(template_path, destination_path):
try: try:
if not os.path.exists(destination_path): if not os.path.exists(destination_path):
# If the destination folder does not exist, copy the template # If the destination folder does not exist, copy the template
shutil.copytree(template_path, destination_path) shutil.copytree(template_path, destination_path)
log.info(f"The folder {Colors.ENDC}{template_path}{Colors.GREEN} has been copied to {Colors.ENDC}{safe_relpath(destination_path)}{Colors.GREEN}") log.info(f"The folder {Colors.ENDC}{template_path}{Colors.GREEN} has been copied to {Colors.ENDC}{safe_relpath(destination_path)}{Colors.GREEN}")
else: else:
log.warning(f"The folder '{Colors.ENDC}{safe_relpath(destination_path)}{Colors.WARNING}' already exists. No files were copied.") log.warning(f"The folder '{Colors.ENDC}{safe_relpath(destination_path)}{Colors.WARNING}' already exists. No files were copied.")
except Exception as e: except Exception as e: # noqa: BLE001
log.critical(f"Copy template error: {Colors.ENDC}{e}") log.critical(f"Copy template error: {Colors.ENDC}{e}")
exit(0) sys.exit(0)
################################################################################################# #################################################################################################
def add_copyright_header(file_path, copyright_text): def add_copyright_header(file_path, copyright_text):
# Lire le contenu du fichier # Lire le contenu du fichier
with open(file_path, 'r', encoding="utf-8") as file: with open(file_path, "r", encoding="utf-8") as file:
content = file.readlines() content = file.readlines()
# Vérifier si le copyright est déjà présent # Vérifier si le copyright est déjà présent
if not any("copyright" in line.lower() for line in content): if not any("copyright" in line.lower() for line in content):
# Ajouter le copyright en en-tête # Ajouter le copyright en en-tête
content.insert(0, f"{copyright_text}\n") content.insert(0, f"{copyright_text}\n")
# Réécrire le fichier avec le copyright ajouté
with open(file_path, 'w', encoding="utf-8") as file:
file.writelines(content)
# Réécrire le fichier avec le copyright ajouté
with open(file_path, "w", encoding="utf-8") as file:
file.writelines(content)
################################################################################################# #################################################################################################
def copy_file_with_copyright(th_file, destination_path, copyright_text): def copy_file_with_copyright(th_file, destination_path, copyright_text):
# Vérifier si le fichier existe # Vérifier si le fichier existe
if os.path.exists(th_file): if os.path.exists(th_file):
# Créer le dossier de destination s'il n'existe pas # Créer le dossier de destination s'il n'existe pas
os.makedirs(destination_path, exist_ok=True) os.makedirs(destination_path, exist_ok=True)
_destFile = sanitize_filename(os.path.basename(th_file)[:-3]) + ".th" _destFile = sanitize_filename(os.path.basename(th_file)[:-3]) + ".th"
# Copier le fichier vers le dossier de destination # Copier le fichier vers le dossier de destination
dest_file = os.path.join(destination_path, _destFile) dest_file = os.path.join(destination_path, _destFile)
shutil.copy(th_file, dest_file) shutil.copy(th_file, dest_file)
# Ajouter le copyright dans l'en-tête si nécessaire # Ajouter le copyright dans l'en-tête si nécessaire
add_copyright_header(dest_file, copyright_text) add_copyright_header(dest_file, copyright_text)
log.debug(f"File {Colors.ENDC}{safe_relpath(th_file)}{Colors.GREEN} has been copied to {Colors.ENDC}{safe_relpath(destination_path)}{Colors.GREEN} with the copyright header added.{Colors.ENDC}") log.debug(
f"File {Colors.ENDC}{safe_relpath(th_file)}{Colors.GREEN} has been copied to {Colors.ENDC}{safe_relpath(destination_path)}{Colors.GREEN} with the copyright header added.{Colors.ENDC}"
)
else: else:
log.error(f"The file .th does not exist {Colors.ENDC}{safe_relpath(th_file)}") log.error(f"The file .th does not exist {Colors.ENDC}{safe_relpath(th_file)}")
global_Data.error_count += 1 global_Data.error_count += 1
################################################################################################# #################################################################################################
# Remplir les template avec les variables vers output_path # # # Remplir les template avec les variables vers output_path # #
################################################################################################# #################################################################################################
def update_template_files(template_path, variables, output_path): def update_template_files(template_path, variables, output_path):
""" """
Process a Therion template file by replacing variables. Process a Therion template file by replacing variables.
Args: Args:
template_path (str): Path to the original template file template_path (str): Path to the original template file
variables (dict): Dictionary of variables to replace variables (dict): Dictionary of variables to replace
output_path (str): Path for the new configuration file output_path (str): Path for the new configuration file
Returns: Returns:
None None
""" """
try: try:
# Read the content of the template file # Read the content of the template file
with open(template_path, 'r', encoding='utf-8') as file: with open(template_path, "r", encoding="utf-8") as file:
content = file.read() content = file.read()
# Replace variables # Replace variables
for var, value in variables.items(): for var, value in variables.items():
# Use regex to replace {variable} with its value # Use regex to replace {variable} with its value
pattern = r'\{' + re.escape(var) + r'\}' pattern = r"\{" + re.escape(var) + r"\}"
content = re.sub(pattern, str(value), content) content = re.sub(pattern, str(value), content)
# Write the new file # Write the new file
with open(output_path, 'w', encoding='utf-8') as file: with open(output_path, "w", encoding="utf-8") as file:
file.write(content) file.write(content)
log.info(f"Update template successfully: {Colors.ENDC}{safe_relpath(output_path)}") log.info(f"Update template successfully: {Colors.ENDC}{safe_relpath(output_path)}")
# Delete the original template file # Delete the original template file
os.remove(template_path) os.remove(template_path)
except FileNotFoundError: except FileNotFoundError:
log.error(f"Template file {Colors.ENDC}{template_path}{Colors.ERROR} not found") log.error(f"Template file {Colors.ENDC}{template_path}{Colors.ERROR} not found")
global_Data.error_count += 1 global_Data.error_count += 1
except PermissionError: except PermissionError:
log.error(f"Insufficient permissions to write the file") log.error("Insufficient permissions to write the file")
global_Data.error_count += 1 global_Data.error_count += 1
except Exception as e: except Exception as e: # noqa: BLE001
log.error(f"An error occurred (update_template_files : {Colors.ENDC}{os.path.basename(template_path)}{Colors.ERROR}) : {Colors.ENDC}{e}") log.error(f"An error occurred (update_template_files : {Colors.ENDC}{os.path.basename(template_path)}{Colors.ERROR}) : {Colors.ENDC}{e}")
global_Data.error_count += 1 global_Data.error_count += 1
################################################################################################# #################################################################################################
def load_text_file_utf8(filepath, short_filename): def load_text_file_utf8(filepath, short_filename):
"""Loads a text file with various encodings and converts it to UTF-8. """Loads a text file with various encodings and converts it to UTF-8.
@@ -642,41 +609,62 @@ def load_text_file_utf8(filepath, short_filename):
""" """
encodings_to_try = [ encodings_to_try = [
'utf-8-sig', # UTF-8 avec BOM "utf-8-sig", # UTF-8 avec BOM
'utf-8', # UTF-8 standard "utf-8", # UTF-8 standard
'windows-1252', # ANSI Windows Europe de l’Ouest "windows-1252", # ANSI Windows Europe de l’Ouest
'iso-8859-15', # ISO-8859-15 (latin9), remplace iso-8859-1 (latin1) "iso-8859-15", # ISO-8859-15 (latin9), remplace iso-8859-1 (latin1)
'iso-8859-1', "iso-8859-1",
] ]
for enc in encodings_to_try: for enc in encodings_to_try:
try: try:
with open(filepath, 'r', encoding=enc) as f: with open(filepath, "r", encoding=enc) as f:
content = f.read() content = f.read()
log.info(f"Open source file: {Colors.ENDC}{short_filename}{Colors.GREEN}, with encoding: {Colors.ENDC}{enc}{Colors.GREEN} and conversion to {Colors.ENDC}utf-8") log.info(
f"Open source file: {Colors.ENDC}{short_filename}{Colors.GREEN}, with encoding: {Colors.ENDC}{enc}{Colors.GREEN} and conversion to {Colors.ENDC}utf-8"
)
message_log = f"* Source file: {short_filename}, encoding: {enc}, conversion to utf-8\n" message_log = f"* Source file: {short_filename}, encoding: {enc}, conversion to utf-8\n"
return content, message_log, enc return content, message_log, enc
except UnicodeDecodeError as e: except UnicodeDecodeError as e:
log.debug(f"Failed {Colors.ENDC}{enc}{Colors.DEBUG} for {Colors.ENDC}{short_filename}{Colors.DEBUG}: {Colors.ENDC}{e}") log.debug(f"Failed {Colors.ENDC}{enc}{Colors.DEBUG} for {Colors.ENDC}{short_filename}{Colors.DEBUG}: {Colors.ENDC}{e}")
continue continue
except Exception as e: except Exception as e: # noqa: BLE001
log.critical(f"Unexpected error while reading {Colors.ENDC}{short_filename}{Colors.CRITICAL}: {e}") log.critical(f"Unexpected error while reading {Colors.ENDC}{short_filename}{Colors.CRITICAL}: {e}")
exit(0) sys.exit(0)
return None, "", None return None, "", None
# Dernier recours : lecture binaire + forçage # Dernier recours : lecture binaire + forçage
try: try:
with open(filepath, 'rb') as f: with open(filepath, "rb") as f:
raw = f.read() raw = f.read()
content = raw.decode('windows-1252', errors='replace') content = raw.decode("windows-1252", errors="replace")
log.warning(f"Force-reading {Colors.ENDC}{short_filename}{Colors.WARNING} with character replacement (windows-1252)") log.warning(f"Force-reading {Colors.ENDC}{short_filename}{Colors.WARNING} with character replacement (windows-1252)")
message = f"* Force-reading source file: {short_filename} with character replacement (windows-1252)\n" message = f"* Force-reading source file: {short_filename} with character replacement (windows-1252)\n"
return content, message, 'windows-1252' return content, message, "windows-1252"
except Exception as e: except Exception as e: # noqa: BLE001
log.critical(f"Failed to read file {Colors.ENDC}{short_filename}{Colors.CRITICAL}: {Colors.ENDC}{e}") log.critical(f"Failed to read file {Colors.ENDC}{short_filename}{Colors.CRITICAL}: {Colors.ENDC}{e}")
exit(0) sys.exit(0)
return None, "", None return None, "", None
#################################################################################################
def read_text_file(filename):
"""Lecture avec prise en charge de plusieurs encodages."""
for encoding in ("utf-8-sig", "cp1252", "latin-1"):
try:
with open(filename, "r", encoding=encoding) as f:
content = f.read()
if encoding != "utf-8-sig":
log.info(f"Fichier : {Colors.ENDC}{safe_relpath(filename)}{Colors.INFO} lu en {Colors.ENDC}{encoding}")
return content
except UnicodeDecodeError:
continue
raise UnicodeError(f"{Colors.ERROR}Impossible de décoder {Colors.ENDC}{filename}")
+70 -72
View File
@@ -1,16 +1,16 @@
""" """
!#############################################################################################! !#############################################################################################!
global_data.py for pyCreateTh.py global_data.py for pyCreateTh.py
!#############################################################################################! !#############################################################################################!
""" """
Version = "2026.01.08" Version = "2026.11.19"
################################################################################################# #################################################################################################
debug_log = False # Mode debug des messages
error_count = 0 # Compteur d'erreurs error_count = 0 # Compteur d'erreurs
## [Survey_Data] default values ## [Survey_Data] default values
Author = "Created by pyCreateTh.py" Author = "Created by pyCreateTh.py"
@@ -28,7 +28,7 @@ templatePath = "./Template"
stationByScrap = 20 stationByScrap = 20
finalTherion_exe = True finalTherion_exe = True
therionPath = "C:/Therion/therion.exe" therionPath = "C:/Therion/therion.exe"
SurveyPrefixName = f"Survey_" SurveyPrefixName = "Survey_"
linesInTh2 = True linesInTh2 = True
stationNamesInTh2 = True stationNamesInTh2 = True
wallLinesInTh2 = True wallLinesInTh2 = True
@@ -39,33 +39,35 @@ parse_tro_files_by_explo = True
################################################################################################# #################################################################################################
THERION_KEYWORDS = { THERION_KEYWORDS = {
"centerline", "centerline",
"endcenterline", "endcenterline",
"date", "date",
"units", "units",
"flags", "flags",
"team", "team",
"calibrate", "calibrate",
"data", "data",
"declination", "declination",
"fix", "fix",
"station", "station",
"equate", "equate",
"cs", "cs",
"extend", "extend",
"infer", "infer",
"explo-team", "explo-team",
"instrument", "instrument",
"grade", "grade",
"clino", "clino",
"compass", "compass",
"length", "length",
"reverse", "reverse",
"topofil", "topofil",
"duplicate", "duplicate",
"not", "not",
} }
#################################################################################################
# tot file template #
################################################################################################# #################################################################################################
totfile = """\t## Survey file: totfile = """\t## Survey file:
\tinput Data/{TH_NAME}.th \tinput Data/{TH_NAME}.th
@@ -81,6 +83,8 @@ totfile = """\t## Survey file:
""" """
#################################################################################################
# Th file template #
################################################################################################# #################################################################################################
thFileDat = """ thFileDat = """
encoding utf-8 encoding utf-8
@@ -93,6 +97,7 @@ survey {SURVEY_NAME} -title "{SURVEY_TITLE}"
\t\t# team "{SURVEY_TEAM}" \t\t# team "{SURVEY_TEAM}"
{FIX_POINTS} {FIX_POINTS}
\t\texplo-date {EXPLO_DATE} \t\texplo-date {EXPLO_DATE}
\t\t# explo-team "{EXPLO_TEAM}" \t\t# explo-team "{EXPLO_TEAM}"
{CORRECTIONS}{DECLINATION} {CORRECTIONS}{DECLINATION}
@@ -109,7 +114,8 @@ endsurvey
{SOURCE} {SOURCE}
""" """
#################################################################################################
# thconfig template (minimal) #
################################################################################################# #################################################################################################
thconfigTemplate = """ thconfigTemplate = """
source "{th_file}" source "{th_file}"
@@ -152,9 +158,9 @@ endscrap
""" """
th2Point = """\tpoint {x} {y} station -name {station}""" th2Point = """\tpoint {x} {y} station -name {station}"""
th2Name = """\tpoint {x} {y} station-name -align tr -scale xs -text {station}""" th2Name = """\tpoint {x} {y} station-name -align tr -scale xs -text {station}"""
th2Line = """ th2Line = """
line u:Shot_Survey line u:Shot_Survey
\t{x1} {y1} \t{x1} {y1}
\t{x2} {y2} \t{x2} {y2}
@@ -173,49 +179,41 @@ endscrap
################################################################################################# #################################################################################################
datumToEPSG = { datumToEPSG = {
# Datums globaux # Datums globaux
"wgs84": "326", # UTM Nord (WGS84) - EPSG:326XX "wgs84": "326", # UTM Nord (WGS84) - EPSG:326XX
"wgs1984": "326", # UTM Nord (WGS84) - EPSG:326XX "wgs1984": "326", # UTM Nord (WGS84) - EPSG:326XX
"etrs89": "258", # UTM Nord (ETRS89) - Europe "etrs89": "258", # UTM Nord (ETRS89) - Europe
# Datums européens
# Datums européens "european1950": "230", # ED50 / UTM Nord - Europe
"european1950": "230", # ED50 / UTM Nord - Europe "ed50": "230",
"ed50": "230", # Datums nord-américains
"nad27": "267", # UTM Nord (NAD27) - Amérique du Nord
# Datums nord-américains "northamericandatum1927": "267",
"nad27": "267", # UTM Nord (NAD27) - Amérique du Nord "northamerican1927": "267",
"northamericandatum1927": "267", "nad83": "269", # UTM Nord (NAD83) - Amérique du Nord
"northamerican1927": "267", "northamericandatum1983": "269",
"nad83": "269", # UTM Nord (NAD83) - Amérique du Nord "northamerican1983": "269",
"northamericandatum1983": "269", # Datums français
"northamerican1983" : "269", "ntf": "275", # UTM Nord (NTF) - France (Paris)
"nouvelletriangulationfrançaise": "275",
# Datums français # Datums africains
"ntf": "275", # UTM Nord (NTF) - France (Paris) "clarke1880": "297", # UTM Nord (Clarke 1880) - Afrique
"nouvelletriangulationfrançaise": "275", # Datums australiens
"agd66": "202", # UTM Nord (AGD66) - Australie
# Datums africains "australiangeodeticdatum1966": "202",
"clarke1880": "297", # UTM Nord (Clarke 1880) - Afrique "australiangeodetic1966": "202",
"agd84": "203", # UTM Nord (AGD84) - Australie
# Datums australiens "australiangeodeticdatum1984": "203",
"agd66": "202", # UTM Nord (AGD66) - Australie "australiangeodetic1984": "203",
"australiangeodeticdatum1966": "202", "gda94": "283", # UTM Nord (GDA94) - Australie
"australiangeodetic1966": "202", "geocentricdatumofaustralia1994": "283",
"agd84": "203", # UTM Nord (AGD84) - Australie "geocentricofaustralia1994": "283",
"australiangeodeticdatum1984": "203", # Datums asiatiques
"australiangeodetic1984": "203", "pulkovo1942": "284", # UTM Nord (Pulkovo 1942) - Russie/CEI
"gda94": "283", # UTM Nord (GDA94) - Australie "beijing1954": "214", # UTM Nord (Beijing 1954) - Chine
"geocentricdatumofaustralia1994": "283", # Datums sud-américains
"geocentricofaustralia1994": "283", "sad69": "291", # UTM Nord (SAD69) - Amérique du Sud
"southamericandatum1969": "291",
# Datums asiatiques "southamerican1969": "291",
"pulkovo1942": "284", # UTM Nord (Pulkovo 1942) - Russie/CEI "sirgas2000": "319", # UTM Nord (SIRGAS 2000) - Amérique Latine
"beijing1954": "214", # UTM Nord (Beijing 1954) - Chine
# Datums sud-américains
"sad69": "291", # UTM Nord (SAD69) - Amérique du Sud
"southamericandatum1969": "291",
"southamerican1969": "291",
"sirgas2000": "319", # UTM Nord (SIRGAS 2000) - Amérique Latine
} }
File diff suppressed because it is too large. Load diff
+474 -449
View File
@@ -1,5 +1,5 @@
######!/usr/bin/env python ######!/usr/bin/env python
# -*- coding: utf8 -*- # -*- coding: utf8 -*- # noqa: UP009
# coding: utf8 # coding: utf8
# Copyright (c) 2020 Xavier Robert <xavier.robert@ird.fr> # Copyright (c) 2020 Xavier Robert <xavier.robert@ird.fr>
@@ -8,498 +8,523 @@
# Modifié Alex 2026 01 04 -> print remplacés par log.xxx # Modifié Alex 2026 01 04 -> print remplacés par log.xxx
""" """
!---------------------------------------------------------! !---------------------------------------------------------!
! ! ! !
! Tro to Therion ! ! Tro to Therion !
! ! ! !
! Code to transform the .tro files ! ! Code to transform the .tro files !
! Visual Topo into files that can ! ! Visual Topo into files that can !
! be used by Therion ! ! be used by Therion !
! ! ! !
! Written by Xavier Robert ! ! Written by Xavier Robert !
! ! ! !
!---------------------------------------------------------! !---------------------------------------------------------!
ENGLISH : ENGLISH :
This code is to transform the .tro file from Visualtopo (http://vtopo.free.fr/) This code is to transform the .tro file from Visualtopo (http://vtopo.free.fr/)
into files that can be read by Therion (http://therion.speleo.sk/). into files that can be read by Therion (http://therion.speleo.sk/).
It reads .tro file and produce one .th file (file with survey data), It reads .tro file and produce one .th file (file with survey data),
and one thconfig file (file that is used to compile and build the survey with Therion). and one thconfig file (file that is used to compile and build the survey with Therion).
TODOS : - Correct the errors in encodings... This is the most important.... TODOS : - Correct the errors in encodings... This is the most important....
- Check all the situations possibles... - Check all the situations possibles...
- Add title to the centerline ! - Add title to the centerline !
""" """
# Do divisions with Reals, not with integers # Do divisions with Reals, not with integers
# Must be at the beginning of the file # Must be at the beginning of the file
from __future__ import division from __future__ import division # noqa: I001, UP010
#from __future__ import unicode_literals
# from __future__ import unicode_literals
import sys, os, wget, logging import sys, os, wget, logging
from urllib.error import HTTPError from urllib.error import HTTPError
# Import Python modules # Import Python modules
#modulesNames = ['sys', 'warnings'] # modulesNames = ['sys', 'warnings']
#for module in modulesNames: # for module in modulesNames:
# try: # try:
# # because we want to import using a variable, do it this way # # because we want to import using a variable, do it this way
# module_obj = __import__(module) # module_obj = __import__(module)
# # create a global object containging our module # # create a global object containging our module
# globals()[module] = module_obj # globals()[module] = module_obj
# except ImportError: # except ImportError:
# sys.exit("ERROR : Module " + module + " not present. \n\n Please, install it \ # sys.exit("ERROR : Module " + module + " not present. \n\n Please, install it \
# \n\n Edit the source code for more information") # \n\n Edit the source code for more information")
from .buildparam import * from .buildparam import *
from .vtopotools import * from .vtopotools import *
from .datathwritetools import * from .datathwritetools import *
from .buildthconfig import * from .buildthconfig import *
import os, logging, sys import os, logging, sys # noqa: F401, F811
from Lib.general_fonctions import Colors, safe_relpath from Lib.general_fonctions import Colors, safe_relpath
import Lib.global_data as global_data import Lib.global_data as global_data # noqa: PLR0402
log = logging.getLogger("Logger") log = logging.getLogger("Logger")
################################################################################################# #################################################################################################
def tro2th(fle_tro_fnme = None, fle_th_fnme = None, def tro2th(
fle_tro_encoding=None, fle_tro_fnme=None,
thlang = u'fr', fle_th_fnme=None,
cavename = None, fle_tro_encoding=None,
icomments = True, icoupe = True, thlang="fr",
ithconfig = True, istructure = True, thconfigfnme = None, cavename=None,
ithc = True, thcpath = None, thcfnme = u'config.thc', icomments=True,
sourcefile = None, xviscale = 1000, xvigrid = 10, scale = 500, icoupe=True,
Errorfiles = True): ithconfig=True,
istructure=True,
""" thconfigfnme=None,
Main function to convert tro to th files. ithc=True,
This is this function that should be called from python. thcpath=None,
thcfnme="config.thc",
INPUTS: sourcefile=None,
fle_tro_fnme : (string) Path and name of the .tro file to convert. xviscale=1000,
if None (value by default), the function does not convert anything xvigrid=10,
but build .thconfig and config.thc files scale=500,
If the path is not given, the function will look in the folder from where it is launched Errorfiles=True,
fle_th_fnme : (string) Path and name of the .th file to create from the .tro file. ):
If None (value by default), this file is created from the .tro file name """
and in the same folder than that .tro file Main function to convert tro to th files.
thlang : (string) String that set the language. 'fr' by default. This is this function that should be called from python.
If you need english, change 'fr' to 'en' in the function definition
set 'fr' for french
set 'en' for english
... other languages are not implemented
cavename : (string) Name of the cave.
If set to None (default value), it is get from the .tro file.
icomments : (Boolean) To add (True, by default) or not (False) comments in the produced files
icoupe : (Boolean) To set (True, by default) or not (False) an extended-elevation layout in the .thconfig file
ithconfig : (Boolean) To set if the thconfig file is created (True, by default) or not
istructure : (Boolean) To set if the structure and the addditional files are created (True, by default) or not
thconfigfnme : (string) Path and name of the thconfig file.
If None (by default), path and name build from the .tro file
ithc : (Boolean) To build (True, by default) or not (False) a config file config.thc
thcpath : (string) Path to the directry that contains the config file called in the cave.thconfig file.
If used with ithc = False, this path is only used for the declaration
in the cave.thconfig
If used with ithc = True, the config file will be written in that directory.
Set to None by default
thcfnme : (string) Name of the config.thc (value by default if set to None or if ommitted)
sourcefile : (list of strings) Define the source files declared in the cave.thconfig
ex :['example.th', 'example.th2', 'example-coupe.th2']
If None or ommitted, it is build from the .tro file or the cavename
xviscale : (Real) Scale of the xvi file.
Set to 1000 by default that corresponds to 1/1000
xvigrid : (Real) Spacing of the grid for the xvi, in meters.
Set 10 by default
scale : (Real) scale of the map
Set to 500 by default that corresponds to 1/500
Errorfiles : (Boolean) If True (by default), an error will be raised if output files exists in the folder
If False, only a warning is raised, and the previous files are erased by the new ones.
Use with caution
OUTPUTS:
Depending of the parameters inputed, several files can be produced
cavename.th : survey data for Therion
cavename.thconfig : file to build the pdf's maps and others
confgi.thc : config file for the .thconfig file.
USAGE:
To build everything
tro2th(fle_tro_fnme = 'Test', fle_th_fnme = 'Test',
thlang = 'fr',
cavename = 'Test',
icomments = True, icoupe = True,
ithconfig = True, thconfigfnme = None,
ithc = True, thcpath = None, thcfnme = 'config.thc',
sourcefiles = None, xviscale = 1000, xvigrid = 10, scale = 500,
Errorfiles = True)
To build only a .th file
tro2th(fle_tro_fnme = 'Test', fle_th_fnme = 'Test',
thlang = 'fr',
cavename = 'Test',
icomments = True, icoupe = True,
ithconfig = False
ithc = False
Errorfiles = True)
To build only a thonfig file, in english, without any comments and without extended elevation layout
tro2th(thlang = 'en',
cavename = 'Test',
icomments = False, icoupe = False,
ithconfig = False, thconfigfnme = None,
ithc = False, thcpath = my/path/to/my/confg/file, thcfnme = 'config.thc',
sourcefiles = ['Test.th', 'Test.th2'], xviscale = 1000, xvigrid = 10, scale = 500,
Errorfiles = True)
Author: Xavier Robert, Lima 2016/06/27
License: CCby-nc
"""
if thlang in [u'fr', u'FR', u'Fr', u'fR']: thlang = u'fr'
elif thlang in [u'en',u'EN', u'En', u'eN']: thlang = u'en'
else: raise NameError(u'ERROR: Language %s not implemented\n'
u' Use "en" instead' % thlang )
log.info(u'____________________________________________________________\n\n\t\tTRO 2 THERION\n____________________________________________________________\n')
if thlang == u'fr':
log.info(u'\nÉcrit par Xavier Robert, Groupe spéléo Vulcain - Lyon, France\n')
elif thlang == u'en':
log.info(u'\nWritten by Xavier Robert, Groupe spéléo Vulcain - Lyon, France\n')
log.info(u'____________________________________________________________\n\n')
coordsyst = None
coordinates = None
if fle_tro_fnme is not None:
if fle_tro_fnme[-4:] != u'.tro':
fle_tro_fnme = fle_tro_fnme + u'.tro'
# check if file exists
if os.path.isfile(fle_tro_fnme) == False :
if thlang == u'fr': raise NameError(u'ERROR : Le fichier {FileNa} n\'existe pas'.format(FileNa=str(fle_tro_fnme)))
elif thlang == u'en': raise NameError(u'ERROR : File {FileNa} does not exist'.format(FileNa=str(fle_tro_fnme)))
if fle_th_fnme is None:
# convert tro file to th file
log.info('1')
entrance, cavename, coordinates, coordsyst, fle_th_fnme = convert_tro(fle_tro_fnme, fle_tro_encoding=fle_tro_encoding,
icomments = icomments, icoupe = icoupe, istructure = istructure,
thlang = thlang, Errorfiles = Errorfiles)
else:
log.info(2)
entrance, cavename, coordinates, coordsyst, fle_th_fnme = convert_tro(fle_tro_fnme, fle_th_fnme, cavename,
icomments = icomments, icoupe = icoupe, istructure = istructure,
thlang = thlang, Errorfiles = Errorfiles)
if thlang == u'fr': log.info(u'\tFichier Therion %s construit à partir des données %s' %(fle_th_fnme, fle_tro_fnme))
elif thlang == u'en': log.info(u'\tFile %s built from %s' %(fle_th_fnme, fle_tro_fnme))
else:
if thlang == u'fr': log.info(u'\tPas de fichier .tro en entrée, pas de fichier de données .th créé...')
elif thlang == u'en': log.info(u'\tNo .tro File input, no .th data file created...')
# Build here the new structure:
if istructure: build_structure(u'cave', Errorfiles = True)
if sourcefile is None: INPUTS:
if fle_th_fnme is None: fle_tro_fnme : (string) Path and name of the .tro file to convert.
if cavename is None: cavename = u'cave' if None (value by default), the function does not convert anything
sourcefile = [cavename.replace(u' ', u'_') + u'.th', but build .thconfig and config.thc files
u'#' + cavename.replace(u' ', u'_') + u'.th2', If the path is not given, the function will look in the folder from where it is launched
u'#' + cavename.replace(u' ', u'_') + u'-coupe.th2'] fle_th_fnme : (string) Path and name of the .th file to create from the .tro file.
else: If None (value by default), this file is created from the .tro file name
sourcefile = [fle_th_fnme, u'#' + fle_th_fnme[0:-4] + u'th2', u'#' + fle_th_fnme[0:-4] + u'-coupe.th2' ] and in the same folder than that .tro file
# Build the dictionnary for the thconfig file thlang : (string) String that set the language. 'fr' by default.
dictcave = [sourcefile, xviscale, xvigrid, cavename, coordsyst, scale] If you need english, change 'fr' to 'en' in the function definition
set 'fr' for french
set 'en' for english
... other languages are not implemented
cavename : (string) Name of the cave.
If set to None (default value), it is get from the .tro file.
icomments : (Boolean) To add (True, by default) or not (False) comments in the produced files
icoupe : (Boolean) To set (True, by default) or not (False) an extended-elevation layout in the .thconfig file
ithconfig : (Boolean) To set if the thconfig file is created (True, by default) or not
istructure : (Boolean) To set if the structure and the additional files are created (True, by default) or not
thconfigfnme : (string) Path and name of the thconfig file.
If None (by default), path and name build from the .tro file
ithc : (Boolean) To build (True, by default) or not (False) a config file config.thc
thcpath : (string) Path to the directory that contains the config file called in the cave.thconfig file.
If used with ithc = False, this path is only used for the declaration
in the cave.thconfig
If used with ithc = True, the config file will be written in that directory.
Set to None by default
thcfnme : (string) Name of the config.thc (value by default if set to None or if omitted)
sourcefile : (list of strings) Define the source files declared in the cave.thconfig
ex :['example.th', 'example.th2', 'example-coupe.th2']
If None or omitted, it is build from the .tro file or the cavename
xviscale : (Real) Scale of the xvi file.
Set to 1000 by default that corresponds to 1/1000
xvigrid : (Real) Spacing of the grid for the xvi, in meters.
Set 10 by default
scale : (Real) scale of the map
Set to 500 by default that corresponds to 1/500
Errorfiles : (Boolean) If True (by default), an error will be raised if output files exists in the folder
If False, only a warning is raised, and the previous files are erased by the new ones.
Use with caution
# build thc file OUTPUTS:
if ithc : Depending of the parameters inputted, several files can be produced
if thcpath is not None : cavename.th : survey data for Therion
# Download the config file from my github page cavename.thconfig : file to build the pdf's maps and others
try: config.thc : config file for the .thconfig file.
wget.download('https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc',
thcpath)
#thcpath + thcfnme)
except HTTPError:
if thcpath[-1] not in ['/', '\\']: thcpath = thcpath + '/'
writethc(thcpath + thcfnme, istructure)
except FileNotFoundError:
if thcpath[-1] not in ['/', '\\']: thcpath = thcpath + '/'
writethc(thcpath + thcfnme, istructure)
else:
# Download the config file from my github page
try:
if istructure: wget.download('https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc',
cavename.replace(u' ', u'_') + '/')
else: wget.download('https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc')
except HTTPError:
writethc(thcfnme, cavename, istructure)
except FileNotFoundError:
writethc(thcfnme, cavename, istructure)
# build thconfig file
# Needs to be change to take in account istructure
if ithconfig :
# write the file
if thconfigfnme is None or thconfigfnme == u'' or thconfigfnme == u' ':
if fle_th_fnme is None: thconfigfnme = cavename.replace(u' ', u'_') + u'.thconfig'
else: thconfigfnme = fle_th_fnme[0:-3] + u'.thconfig'
if thcpath is not None:
thcfnme = thcpath + thcfnme
writethconfig(cavename.replace(u' ', u'_') + thconfigfnme, icomments, icoupe, thlang,
dictcave,
ithc, thcfnme)
else:
thcfnme = thcfnme
writethconfig(cavename.replace(u' ', u'_') + thconfigfnme, icomments, icoupe, thlang,
dictcave,
ithc, cavename.replace(u' ', u'_') + u'/config.thc')
if istructure: USAGE:
# build cavename-tot.th file To build everything
f3w = open(cavename.replace(u' ', u'_') + '/' + cavename.replace(u' ', u'_') + '-tot.th', 'w') tro2th(fle_tro_fnme = 'Test', fle_th_fnme = 'Test',
write_thtot(f3w, cavename, icomments, thlang) thlang = 'fr',
f3w.closed cavename = 'Test',
log.info(u'\tFile ' + cavename.replace(u' ', u'_') + u'/' + cavename.replace(u' ', u'_') + u'-tot.th written...\n') icomments = True, icoupe = True,
ithconfig = True, thconfigfnme = None,
ithc = True, thcpath = None, thcfnme = 'config.thc',
sourcefiles = None, xviscale = 1000, xvigrid = 10, scale = 500,
Errorfiles = True)
# build cavename-maps.th file To build only a .th file
f4w = open(cavename.replace(u' ', u'_') + u'/' + cavename.replace(u' ', u'_') + '-maps.th', 'w') tro2th(fle_tro_fnme = 'Test', fle_th_fnme = 'Test',
write_thmaps(f4w, cavename, icomments, thlang) thlang = 'fr',
f4w.closed cavename = 'Test',
log.info(u'\tFile ' + cavename.replace(u' ', u'_') + u'/' + cavename.replace(u' ', u'_') + u'-maps.th written...\n\n') icomments = True, icoupe = True,
ithconfig = False
ithc = False
Errorfiles = True)
# build Legends/entrances-coordinates.th file To build only a thconfig file, in english, without any comments and without extended elevation layout
f5w = open(cavename.replace(u' ', u'_') + '/Legends/entrances_coordinates.th', 'w') tro2th(thlang = 'en',
write_thcoords(f5w, cavename, coordinates, coordsyst, icomments, thlang) cavename = 'Test',
f5w.closed icomments = False, icoupe = False,
log.info(u'\tFile ' + cavename.replace(u' ', u'_') + u'/Legends/entrances_coordinates.th written...\n\n') ithconfig = False, thconfigfnme = None,
ithc = False, thcpath = my/path/to/my/config/file, thcfnme = 'config.thc',
sourcefiles = ['Test.th', 'Test.th2'], xviscale = 1000, xvigrid = 10, scale = 500,
Errorfiles = True)
log.info(u'____________________________________________________________') Author: Xavier Robert, Lima 2016/06/27
log.info(u'')
License: CCby-nc
return """
if thlang in ["fr", "FR", "Fr", "fR"]:
thlang = "fr"
elif thlang in ["en", "EN", "En", "eN"]:
thlang = "en"
else:
raise NameError(
"ERROR: Language %s not implemented\n" # noqa: UP031
' Use "en" instead' % thlang
)
log.info("____________________________________________________________\n\n\t\tTRO 2 THERION\n____________________________________________________________\n")
if thlang == "fr":
log.info("\nÉcrit par Xavier Robert, Groupe spéléo Vulcain - Lyon, France\n")
elif thlang == "en":
log.info("\nWritten by Xavier Robert, Groupe spéléo Vulcain - Lyon, France\n")
log.info("____________________________________________________________\n\n")
coordsyst = None
coordinates = None
if fle_tro_fnme is not None:
if fle_tro_fnme[-4:] != ".tro":
fle_tro_fnme = fle_tro_fnme + ".tro"
# check if file exists
if os.path.isfile(fle_tro_fnme) == False:
if thlang == "fr":
raise NameError("ERROR : Le fichier {FileNa} n'existe pas".format(FileNa=str(fle_tro_fnme))) # noqa: UP032
elif thlang == "en":
raise NameError("ERROR : File {FileNa} does not exist".format(FileNa=str(fle_tro_fnme))) # noqa: UP032
if fle_th_fnme is None:
# convert tro file to th file
log.info("1")
entrance, cavename, coordinates, coordsyst, fle_th_fnme = convert_tro(
fle_tro_fnme, fle_tro_encoding=fle_tro_encoding, icomments=icomments, icoupe=icoupe, istructure=istructure, thlang=thlang, Errorfiles=Errorfiles
)
else:
log.info(2)
entrance, cavename, coordinates, coordsyst, fle_th_fnme = convert_tro( # noqa: RUF059
fle_tro_fnme, fle_th_fnme, cavename, icomments=icomments, icoupe=icoupe, istructure=istructure, thlang=thlang, Errorfiles=Errorfiles
)
if thlang == "fr":
log.info("\tFichier Therion %s construit à partir des données %s" % (fle_th_fnme, fle_tro_fnme)) # noqa: UP031
elif thlang == "en":
log.info("\tFile %s built from %s" % (fle_th_fnme, fle_tro_fnme)) # noqa: UP031
else:
if thlang == "fr":
log.info("\tPas de fichier .tro en entrée, pas de fichier de données .th créé...")
elif thlang == "en":
log.info("\tNo .tro File input, no .th data file created...")
# Build here the new structure:
if istructure:
build_structure("cave", Errorfiles=True)
if sourcefile is None:
if fle_th_fnme is None:
if cavename is None:
cavename = "cave"
sourcefile = [cavename.replace(" ", "_") + ".th", "#" + cavename.replace(" ", "_") + ".th2", "#" + cavename.replace(" ", "_") + "-coupe.th2"]
else:
sourcefile = [fle_th_fnme, "#" + fle_th_fnme[0:-4] + "th2", "#" + fle_th_fnme[0:-4] + "-coupe.th2"]
# Build the dictionary for the thconfig file
dictcave = [sourcefile, xviscale, xvigrid, cavename, coordsyst, scale]
# build thc file
if ithc:
if thcpath is not None:
# Download the config file from my github page
try:
wget.download("https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc", thcpath)
# thcpath + thcfnme)
except HTTPError:
if thcpath[-1] not in ["/", "\\"]:
thcpath = thcpath + "/"
writethc(thcpath + thcfnme, istructure)
except FileNotFoundError:
if thcpath[-1] not in ["/", "\\"]:
thcpath = thcpath + "/"
writethc(thcpath + thcfnme, istructure)
else:
# Download the config file from my github page
try:
if istructure:
wget.download("https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc", cavename.replace(" ", "_") + "/")
else:
wget.download("https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc")
except HTTPError:
writethc(thcfnme, cavename, istructure)
except FileNotFoundError:
writethc(thcfnme, cavename, istructure)
# build thconfig file
# Needs to be change to take in account istructure
if ithconfig:
# write the file
if thconfigfnme is None or thconfigfnme == "" or thconfigfnme == " ":
if fle_th_fnme is None:
thconfigfnme = cavename.replace(" ", "_") + ".thconfig"
else:
thconfigfnme = fle_th_fnme[0:-3] + ".thconfig"
if thcpath is not None:
thcfnme = thcpath + thcfnme
writethconfig(cavename.replace(" ", "_") + thconfigfnme, icomments, icoupe, thlang, dictcave, ithc, thcfnme)
else:
thcfnme = thcfnme # noqa: PLW0127
writethconfig(cavename.replace(" ", "_") + thconfigfnme, icomments, icoupe, thlang, dictcave, ithc, cavename.replace(" ", "_") + "/config.thc")
if istructure:
# build cavename-tot.th file
f3w = open(cavename.replace(" ", "_") + "/" + cavename.replace(" ", "_") + "-tot.th", "w") # noqa: SIM115
write_thtot(f3w, cavename, icomments, thlang)
f3w.closed # noqa: B018
log.info("\tFile " + cavename.replace(" ", "_") + "/" + cavename.replace(" ", "_") + "-tot.th written...\n")
# build cavename-maps.th file
f4w = open(cavename.replace(" ", "_") + "/" + cavename.replace(" ", "_") + "-maps.th", "w") # noqa: SIM115
write_thmaps(f4w, cavename, icomments, thlang)
f4w.closed # noqa: B018
log.info("\tFile " + cavename.replace(" ", "_") + "/" + cavename.replace(" ", "_") + "-maps.th written...\n\n")
# build Legends/entrances-coordinates.th file
f5w = open(cavename.replace(" ", "_") + "/Legends/entrances_coordinates.th", "w") # noqa: SIM115
write_thcoords(f5w, cavename, coordinates, coordsyst, icomments, thlang)
f5w.closed # noqa: B018
log.info("\tFile " + cavename.replace(" ", "_") + "/Legends/entrances_coordinates.th written...\n\n")
log.info("____________________________________________________________")
log.info("")
return # noqa: PLR1711
################################################################################################# #################################################################################################
def build_structure(cavename, Errorfiles = True): def build_structure(cavename, Errorfiles=True):
""" """
Check and build if needed the new structure: Check and build if needed the new structure:
-Cave/ -Cave/
-Data/ -Data/
-cavename.th -cavename.th
(-cavename.th2) (-cavename.th2)
-Legends/ -Legends/
-entrances_coordinates.th -entrances_coordinates.th
-Outputs/ -Outputs/
-outputs.txt -outputs.txt
-Cavename.thconfig -Cavename.thconfig
-cavename-tot.th -cavename-tot.th
-cavename-maps.th -cavename-maps.th
-config.thc -config.thc
INPUTS:
cavename = name of the cave that is used to build all the folders and file structure
Errorfiles = Boolean; If True (Default), the program stops if the structure already exists
If False or none, if the structure exists, it is erased
OUTPUTS: INPUTS:
None, except a new structure cavename = name of the cave that is used to build all the folders and file structure
Errorfiles = Boolean; If True (Default), the program stops if the structure already exists
If False or none, if the structure exists, it is erased
USAGE: OUTPUTS:
build_structure(cavename, Errorfiles) None, except a new structure
""" USAGE:
build_structure(cavename, Errorfiles)
# check if the folder cavename/ exists
if os.path.exists(cavename.replace(u' ', u'_')): """
if Errorfiles:
# Stop # check if the folder cavename/ exists
raise NameError(u'ERROR : Folder {FileNa} does exist'.format(FileNa=str(cavename.replace(u' ', u'_')))) if os.path.exists(cavename.replace(" ", "_")):
else: if Errorfiles:
log.warning(f"I have erased the folder {Colors.ENDC}{cavename.replace(u' ', u'_')}") # Stop
if not os.path.exists(cavename.replace(u' ', u'_') + u'/Data'): os.mkdir(cavename.replace(u' ', u'_') + u'/Data') raise NameError("ERROR : Folder {FileNa} does exist".format(FileNa=str(cavename.replace(" ", "_"))))
if not os.path.exists(cavename.replace(u' ', u'_') + u'/Legends'): os.mkdir(cavename.replace(u' ', u'_') + u'/Legends') else:
if not os.path.exists(cavename.replace(u' ', u'_') + u'/Outputs'): log.warning(f"I have erased the folder {Colors.ENDC}{cavename.replace(' ', '_')}")
os.mkdir(cavename.replace(u' ', u'_') + u'/Outputs') if not os.path.exists(cavename.replace(" ", "_") + "/Data"):
# Add outputs.txt file os.mkdir(cavename.replace(" ", "_") + "/Data")
mkfle_output_txt(cavename.replace(u' ', u'_')) if not os.path.exists(cavename.replace(" ", "_") + "/Legends"):
# - if no, create it and create the other files os.mkdir(cavename.replace(" ", "_") + "/Legends")
else: if not os.path.exists(cavename.replace(" ", "_") + "/Outputs"):
# Create the subfolders os.mkdir(cavename.replace(" ", "_") + "/Outputs")
os.mkdir(cavename.replace(u' ', u'_')) # Add outputs.txt file
os.mkdir(cavename.replace(u' ', u'_') + u'/Data') mkfle_output_txt(cavename.replace(" ", "_"))
os.mkdir(cavename.replace(u' ', u'_') + u'/Outputs') # - if no, create it and create the other files
# Add outputs.txt file else:
mkfle_output_txt(cavename.replace(u' ', u'_')) # Create the subfolder
os.mkdir(cavename.replace(u' ', u'_') + u'/Legends') os.mkdir(cavename.replace(" ", "_"))
os.mkdir(cavename.replace(" ", "_") + "/Data")
return os.mkdir(cavename.replace(" ", "_") + "/Outputs")
# Add outputs.txt file
mkfle_output_txt(cavename.replace(" ", "_"))
os.mkdir(cavename.replace(" ", "_") + "/Legends")
return # noqa: PLR1711
################################################################################################# #################################################################################################
def mkfle_output_txt(cavename): def mkfle_output_txt(cavename):
""" """
Build the file Output.txt in the folder cavename/Outputs/ Build the file Output.txt in the folder cavename/Outputs/
INPUTS: INPUTS:
cavename = name of the cave cavename = name of the cave
OUTPUTS: OUTPUTS:
None None
USAGE: USAGE:
create_output_txt(cavename) create_output_txt(cavename)
""" """
# Open the cavename/Outputs/outputs.txt file # Open the cavename/Outputs/outputs.txt file
f1w = open(cavename.replace(u' ', u'_') + u'/Outputs/outputs.txt','w') f1w = open(cavename.replace(" ", "_") + "/Outputs/outputs.txt", "w") # noqa: SIM115
f1w.write(u'Folder where Therion outputs are exported \n\n') f1w.write("Folder where Therion outputs are exported \n\n")
# close the cavename/Outputs/outputs.txt file # close the cavename/Outputs/outputs.txt file
f1w.closed f1w.closed # noqa: B018
log.info(u'\tFile ' + cavename.replace(u' ', u'_') + u'/Outputs/outputs.txt written...') log.info("\tFile " + cavename.replace(" ", "_") + "/Outputs/outputs.txt written...")
return return # noqa: PLR1711
################################################################################################# #################################################################################################
def convert_tro(fle_tro_fnme, fle_tro_encoding=None, fle_th_fnme = None, cavename = None, def convert_tro(fle_tro_fnme, fle_tro_encoding=None, fle_th_fnme=None, cavename=None, icomments=True, icoupe=True, istructure=True, thlang="fr", Errorfiles=True):
icomments = True, icoupe = True, istructure = True, thlang = u'fr', Errorfiles = True): """
""" Function that manages the tro 2 th conversion
Function that manages the tro 2 th conversion
INPUTS:
fle_tro_fnme : path and file name of the .tro file to convert
fle_th_fnme : path and file name of the .th file to create.
If ommitted, set to None, and this varaible will be set in function of the fle_tro_fnme or cavename
cavename : Name of the cave. If ommitted, it is set to None, and it is get from the .tro file
icomments : (Boolean) To add (True, by default) or not (False) comments in the produced files
icoupe : (Boolean) To set (True, by default) or not (False) an extended-elevation layout in the .thconfig file
istructure : (Boolean) To set if the structure and the addditional files are created (True, by default) or not
thlang : (string) String that set the language. 'fr' by default.
If you need english, change 'fr' to 'en' in the function definition
set 'fr' for french
set 'en' for english
Errorfiles : True (by default if ommitted) to get an error if the .th file already exists.
False if only a warning...
OUTPUTS:
new .th file with surveyed data for Therion
cavename : Name of the cave from the .tro file
coordinates : Coordinates of the entrance (in m)
coordsyst : Coordinates system used by the .tro file
entrance : Entrance station
USAGE:
cavename, coordsyst = convert_tro(fle_tro_fnme, [fle_th_fnme = fle_th_fnme, cavename = cavename, Errorfiles = Errorfiles])
fle_th_fnme, cavename and Errorfiles can be ommitted.
Author: Xavier Robert, Lima 2016/06/27
License: CCby-nc
"""
#from codecs import open
# Initialization of some variables...
#xcoord=0.
#ycoord=0.
#alt=0.
# open the .tro survey
log.info(f"Processing VisualTopo file: {Colors.ENDC}{safe_relpath(fle_tro_fnme)}")
# print(' ')
fle_tro = open(fle_tro_fnme, 'r', encoding=fle_tro_encoding)
# read the .tro file
try:
lines = fle_tro.readlines()
# change the encoding
lines = convert_text(lines)
except UnicodeDecodeError:
# find the line where there is the error
# initiate the line number
lineNumber = 1
try:
# read the first line
line = fle_tro.redline()
while line:
# update the line number
lineNumber += 1
# read the next line
line = fle_tro.readline()
except UnicodeDecodeError:
log.error(f"Special or accentuated character not supporter line {Colors.ENDC}{lineNumber}{Colors.ERROR}, correct the input file")
global_data.error_count += 1
# read the header
coordinates = None
cavename, coordinates, coordsyst, club, entrance, versionfle = read_vtopo_header(lines)
if cavename is None or cavename == '' or cavename == ' ':
cavename = u'cave'
if fle_th_fnme is None:
fle_th_fnme = cavename.replace(u' ', u'_') + u'.th'
log.info (fle_th_fnme)
if fle_th_fnme[-3:] != u'.th':
fle_th_fnme = fle_th_fnme + u'.th'
# Build here the new structure:
if istructure: build_structure(cavename, Errorfiles)
# check if file exists... INPUTS:
checkfiles(fle_th_fnme, Errorfiles) fle_tro_fnme : path and file name of the .tro file to convert
fle_th_fnme : path and file name of the .th file to create.
# open the .th file If omitted, set to None, and this variable will be set in function of the fle_tro_fnme or cavename
if istructure: fle_th = open (cavename.replace(u' ', u'_') + '/Data/' + fle_th_fnme, 'w') cavename : Name of the cave. If omitted, it is set to None, and it is get from the .tro file
else: fle_th = open (fle_th_fnme, 'w') icomments : (Boolean) To add (True, by default) or not (False) comments in the produced files
icoupe : (Boolean) To set (True, by default) or not (False) an extended-elevation layout in the .thconfig file
# write the .th header istructure : (Boolean) To set if the structure and the additional files are created (True, by default) or not
writeheader_th(fle_th, cavename, entrance) thlang : (string) String that set the language. 'fr' by default.
If you need english, change 'fr' to 'en' in the function definition
# initiate variables set 'fr' for french
i = 0 set 'en' for english
iline = []
dataold = []
# get line numbers of the lines beginning with 'Param'
for line in lines:
if u'Param' in line: iline.append(i)
i+=1
for j in iline:
# read the settings of the survey
settings, comments = read_settings(lines[j].replace(u'\n', u''))
# read the data from the tro file
data = read_data(lines, settings, j, iline)
# write centerline header
writecenterlineheader(fle_th, entrance, settings, comments, data, coordsyst, coordinates, club,
icomments, thlang)
# write the data to the .th file Errorfiles : True (by default if omitted) to get an error if the .th file already exists.
writedata(fle_th, settings, data, dataold) False if only a warning...
OUTPUTS:
# write the end of the centerline in the .th file new .th file with surveyed data for Therion
fle_th.write(u'\n\tendcenterline\n\n') cavename : Name of the cave from the .tro file
dataold = data coordinates : Coordinates of the entrance (in m)
# write the end of the survey in the .th file coordsyst : Coordinates system used by the .tro file
fle_th.write(u'\nendsurvey\n') entrance : Entrance station
fle_th.close
USAGE:
#print (fle_th_fnme) cavename, coordsyst = convert_tro(fle_tro_fnme, [fle_th_fnme = fle_th_fnme, cavename = cavename, Errorfiles = Errorfiles])
fle_th_fnme, cavename and Errorfiles can be omitted.
if thlang == u'fr': log.info(f"Fichier Therion {Colors.ENDC}{fle_th_fnme}{Colors.INFO} écrit !")
elif thlang == u'en': log.info(f"Therion file {Colors.ENDC}{fle_th_fnme}{Colors.INFO} written!") Author: Xavier Robert, Lima 2016/06/27
return entrance, cavename, coordinates, coordsyst, fle_th_fnme License: CCby-nc
"""
# from codecs import open
# Initialization of some variables...
# xcoord=0.
# ycoord=0.
# alt=0.
# open the .tro survey
log.info(f"Processing VisualTopo file: {Colors.ENDC}{safe_relpath(fle_tro_fnme)}")
# print(' ')
fle_tro = open(fle_tro_fnme, "r", encoding=fle_tro_encoding) # noqa: SIM115
# read the .tro file
try:
lines = fle_tro.readlines()
# change the encoding
lines = convert_text(lines)
except UnicodeDecodeError:
# find the line where there is the error
# initiate the line number
lineNumber = 1
try:
# read the first line
line = fle_tro.redline()
while line:
# update the line number
lineNumber += 1
# read the next line
line = fle_tro.readline()
except UnicodeDecodeError:
log.error(f"Special or accentuated character not supporter line {Colors.ENDC}{lineNumber}{Colors.ERROR}, correct the input file")
global_data.error_count += 1
# read the header
coordinates = None
cavename, coordinates, coordsyst, club, entrance, versionfle = read_vtopo_header(lines) # noqa: RUF059
if cavename is None or cavename == "" or cavename == " ":
cavename = "cave"
if fle_th_fnme is None:
fle_th_fnme = cavename.replace(" ", "_") + ".th"
log.info(fle_th_fnme)
if fle_th_fnme[-3:] != ".th":
fle_th_fnme = fle_th_fnme + ".th"
# Build here the new structure:
if istructure:
build_structure(cavename, Errorfiles)
# check if file exists...
checkfiles(fle_th_fnme, Errorfiles)
# open the .th file
if istructure:
fle_th = open(cavename.replace(" ", "_") + "/Data/" + fle_th_fnme, "w") # noqa: SIM115
else:
fle_th = open(fle_th_fnme, "w") # noqa: SIM115
# write the .th header
writeheader_th(fle_th, cavename, entrance)
# initiate variables
i = 0
iline = []
dataold = []
# get line numbers of the lines beginning with 'Param'
for line in lines:
if "Param" in line:
iline.append(i)
i += 1 # noqa: SIM113
for j in iline:
# read the settings of the survey
settings, comments = read_settings(lines[j].replace("\n", ""))
# read the data from the tro file
data = read_data(lines, settings, j, iline)
# write centerline header
writecenterlineheader(fle_th, entrance, settings, comments, data, coordsyst, coordinates, club, icomments, thlang, cavename)
# write the data to the .th file
writedata(fle_th, settings, data, dataold)
# write the end of the centerline in the .th file
fle_th.write("\n\tendcenterline\n\n")
dataold = data
# write the end of the survey in the .th file
fle_th.write("\nendsurvey\n")
fle_th.close # noqa: B018
# print (fle_th_fnme)
if thlang == "fr":
log.info(f"Fichier Therion {Colors.ENDC}{fle_th_fnme}{Colors.INFO} écrit !")
elif thlang == "en":
log.info(f"Therion file {Colors.ENDC}{fle_th_fnme}{Colors.INFO} written!")
return entrance, cavename, coordinates, coordsyst, fle_th_fnme
################################################################################################# #################################################################################################
if __name__ == u'__main__': if __name__ == "__main__":
# initiate variables
# initiate variables # run the transformation
tro2th()
# run the transformation
tro2th()
File diff suppressed because it is too large. Load diff
+54 -49
View File
@@ -1,30 +1,31 @@
""" """
!############################################################################################# !#############################################################################################
therion.py for pyCreateTh.py therion.py for pyCreateTh.py
!############################################################################################# !#############################################################################################
""" """
import tempfile, shutil, os, re, logging, threading, subprocess, time import tempfile, shutil, os, re, logging, threading, subprocess, time # noqa: I001
from os.path import join from os.path import join
import Lib.global_data as global_data import Lib.global_data as global_data # noqa: PLR0402
from Lib.general_fonctions import Colors from Lib.general_fonctions import Colors, safe_relpath
log = logging.getLogger("Logger") log = logging.getLogger("Logger")
#################################################################################################
#################################################################################################
# Compilation Therion 'Template' (version sans blocage) # # Compilation Therion 'Template' (version sans blocage) #
# Compiler une configuration générée dynamiquement à partir d'un template texte. # # Compiler une configuration générée dynamiquement à partir d'un template texte. #
################################################################################################# #################################################################################################
def compile_template(template, template_args, totReadMeError = "", **kwargs ): def compile_template(template, template_args, totReadMeError="", **kwargs):
logfile = "" logfile = ""
tmpdir = None tmpdir = None
try: try:
tmpdir = tempfile.mkdtemp() tmpdir = tempfile.mkdtemp()
config = template.format(**template_args, tmpdir=tmpdir.replace("\\", "/")) config = template.format(**template_args, tmpdir=tmpdir.replace("\\", "/"))
log.debug(f"{config}\n") log.debug(f"{config}\n")
config_file = join(tmpdir, "config.thconfig") config_file = join(tmpdir, "config.thconfig")
@@ -37,44 +38,46 @@ def compile_template(template, template_args, totReadMeError = "", **kwargs ):
tmp.flush() tmp.flush()
# Exécution de Therion # Exécution de Therion
result = subprocess.run( result = subprocess.run( # noqa: PLW1510
[therion_path, config_file, "-l", log_file], [therion_path, config_file, "-l", log_file],
stdin=subprocess.DEVNULL, # Évite toute attente d'entrée clavier stdin=subprocess.DEVNULL, # Évite toute attente d'entrée clavier
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, stderr=subprocess.STDOUT,
text=True, text=True,
timeout=kwargs.get("timeout", 30), timeout=kwargs.get("timeout", 30),
errors="replace" errors="replace",
) )
# Lecture du fichier log # Lecture du fichier log
try: try:
with open(log_file, "r", encoding="cp1252", errors="replace") as f: with open(log_file, "r", encoding="cp1252", errors="replace") as f:
logfile = f.read() logfile = f.read()
except Exception as log_err: except Exception as log_err: # noqa: BLE001
log.warning(f"Could not read Therion log: {Colors.ENDC}{log_err}") log.warning(f"Could not read Therion log: {Colors.ENDC}{log_err}")
# Analyse du code retour # Analyse du code retour
if result.returncode != 0 or "press any key" in result.stdout.lower(): if result.returncode != 0 or "press any key" in result.stdout.lower():
selector_value = template_args['selector'] selector_value = template_args["selector"]
log.error(f"Therion compilation {Colors.ENDC}{selector_value}{Colors.ERROR}, failed with return code: {Colors.ENDC}{result.returncode}\n{Colors.WHITE}{result.stdout}") log.error(
f"Therion compilation {Colors.ENDC}{selector_value}{Colors.ERROR}, failed with return code: {Colors.ENDC}{result.returncode}\n{Colors.WHITE}{result.stdout}"
)
totReadMeError += f"\tTherion compilation {selector_value}, failed with return code: {result.returncode}\n" totReadMeError += f"\tTherion compilation {selector_value}, failed with return code: {result.returncode}\n"
global_data.error_count += 1 global_data.error_count += 1
return "Therion error", tmpdir, totReadMeError return "Therion error", tmpdir, totReadMeError
stat = get_stats_from_log(logfile) stat = get_stats_from_log(logfile)
log.info(f"Therion compilation successful, length: {Colors.ENDC}{stat["length"]}m{Colors.INFO}, depth: {Colors.ENDC}{stat["depth"]}m") log.info(f"Therion compilation successful, length: {Colors.ENDC}{stat['length']}m{Colors.INFO}, depth: {Colors.ENDC}{stat['depth']}m")
return logfile, tmpdir, totReadMeError return logfile, tmpdir, totReadMeError
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
log.error(f"Therion process timed out and was terminated: {Colors.ENDC}{logfile}") log.error(f"Therion process timed out and was terminated: {Colors.ENDC}{logfile}")
totReadMeError += f"\tTherion process timed out and was terminated\n" totReadMeError += "\tTherion process timed out and was terminated\n"
global_data.error_count += 1 global_data.error_count += 1
return "Therion error", tmpdir, totReadMeError return "Therion error", tmpdir, totReadMeError
except Exception as e: except Exception as e: # noqa: BLE001
log.error(f"Therion template compilation error: {Colors.ENDC}{e}") log.error(f"Therion template compilation error: {Colors.ENDC}{e}")
totReadMeError += f"\tTherion template compilation error: {e}\n" totReadMeError += f"\tTherion template compilation error: {e}\n"
global_data.error_count += 1 global_data.error_count += 1
@@ -84,11 +87,11 @@ def compile_template(template, template_args, totReadMeError = "", **kwargs ):
if kwargs.get("cleanup", True) and tmpdir: if kwargs.get("cleanup", True) and tmpdir:
try: try:
shutil.rmtree(tmpdir) shutil.rmtree(tmpdir)
except Exception as cleanup_err: except Exception as cleanup_err: # noqa: BLE001
log.warning(f"Could not delete temp directory: {Colors.ENDC}{cleanup_err}") log.warning(f"Could not delete temp directory: {Colors.ENDC}{cleanup_err}")
################################################################################################# #################################################################################################
# Compilation Therion (version sans blocage) # # Compilation Therion (version sans blocage) #
################################################################################################# #################################################################################################
def compile_file(filename, **kwargs): def compile_file(filename, **kwargs):
@@ -97,17 +100,12 @@ def compile_file(filename, **kwargs):
therion_path = kwargs.get("therion_path", "therion") therion_path = kwargs.get("therion_path", "therion")
timeout = kwargs.get("timeout", 240) timeout = kwargs.get("timeout", 240)
log.info(f"Start therion [Therion Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.GREEN}], compilation file") log.info(f"Start therion [Therion Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.GREEN}], compilation file")
def run(): def run():
try: try:
process = subprocess.Popen( process = subprocess.Popen(
[therion_path, filename, "-l", log_file], [therion_path, filename, "-l", log_file], cwd=tmpdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, bufsize=1
cwd=tmpdir,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
bufsize=1
) )
last_output_time = time.time() last_output_time = time.time()
@@ -115,7 +113,7 @@ def compile_file(filename, **kwargs):
def read_output(proc): def read_output(proc):
nonlocal last_output_time nonlocal last_output_time
try: try:
for line in iter(proc.stdout.readline, ''): for line in iter(proc.stdout.readline, ""):
line = line.rstrip() line = line.rstrip()
last_output_time = time.time() # ← reset du timer ici last_output_time = time.time() # ← reset du timer ici
lower_line = line.lower() lower_line = line.lower()
@@ -123,18 +121,18 @@ def compile_file(filename, **kwargs):
if "average loop error" in lower_line: if "average loop error" in lower_line:
continue continue
elif "error" in lower_line: elif "error" in lower_line:
log.error(f"[Therion_Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.ERROR}] {Colors.ENDC}{line}") log.error(f"[Therion_Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.ERROR}] {Colors.ENDC}{line}")
elif "warning" in lower_line: elif "warning" in lower_line:
if not any(msg in line for msg in [ if not any(msg in line for msg in ["invalid scrap outline", "average loop error", "multiple scrap outer outlines not supported yet"]):
"invalid scrap outline", log.warning(
"average loop error", f"[Therion compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.WARNING}] {Colors.ENDC}{safe_relpath(line)}"
"multiple scrap outer outlines not supported yet" )
]):
log.warning(f"[Therion compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.WARNING}] {Colors.ENDC}{line}")
else: else:
log.debug(f"[Therion compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.DEBUG}] {Colors.ENDC}{line}") log.debug(f"[Therion compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.DEBUG}] {Colors.ENDC}{line}")
except Exception as e: except Exception as e: # noqa: BLE001
log.warning(f"Reading Therion [Therion_Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.WARNING}], output: {Colors.ENDC}{e}") log.warning(
f"Reading Therion [Therion_Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.WARNING}], output: {Colors.ENDC}{e}"
)
output_thread = threading.Thread(target=read_output, args=(process,)) output_thread = threading.Thread(target=read_output, args=(process,))
output_thread.start() output_thread.start()
@@ -143,7 +141,9 @@ def compile_file(filename, **kwargs):
while output_thread.is_alive(): while output_thread.is_alive():
output_thread.join(timeout=1) output_thread.join(timeout=1)
if time.time() - last_output_time > timeout: if time.time() - last_output_time > timeout:
log.error(f"Therion compilation [Therion_Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.ERROR}], timed out after {Colors.ENDC}{timeout}{Colors.ERROR} seconds of inactivity. Killing process...") log.error(
f"Therion compilation [Therion_Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.ERROR}], timed out after {Colors.ENDC}{timeout}{Colors.ERROR} seconds of inactivity. Killing process..."
)
global_data.error_count += 1 global_data.error_count += 1
process.kill() process.kill()
break break
@@ -152,13 +152,15 @@ def compile_file(filename, **kwargs):
process.wait() process.wait()
if process.returncode != 0: if process.returncode != 0:
log.error(f"Therion [Therion_Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.ERROR}], returned error code {Colors.ENDC}{process.returncode}") log.error(
f"Therion [Therion_Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.ERROR}], returned error code {Colors.ENDC}{process.returncode}"
)
global_data.error_count += 1 global_data.error_count += 1
else: else:
log.info(f"Therion file: [Therion Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.GREEN}], compilation succeeded") log.info(f"Therion file: [Therion Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.GREEN}], compilation succeeded")
except Exception as e: except Exception as e: # noqa: BLE001
log.error(f"Therion file: [Therion Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.ERROR}], compilation error: {Colors.ENDC}{e}") log.error(f"Therion file: [Therion Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.ERROR}], compilation error: {Colors.ENDC}{e}")
global_data.error_count += 1 global_data.error_count += 1
# Lancer le thread principal pour cette compilation et le retourner # Lancer le thread principal pour cette compilation et le retourner
@@ -166,6 +168,7 @@ def compile_file(filename, **kwargs):
thread.start() thread.start()
return thread return thread
################################################################################################# #################################################################################################
def compile_file_th(filepath, **kwargs): def compile_file_th(filepath, **kwargs):
template = """source {filepath} template = """source {filepath}
@@ -174,7 +177,7 @@ def compile_file_th(filepath, **kwargs):
endlayout endlayout
""" """
template_args = {"filepath": filepath} template_args = {"filepath": filepath}
logs, _, = compile_template(template, template_args, cleanup=True, **kwargs) logs, _ = compile_template(template, template_args, cleanup=True, **kwargs)
return logs return logs
@@ -186,27 +189,29 @@ fr_depthre = re.compile(r".*Longueur totale verticale =\s*(\S+)m")
en_lengthre = re.compile(r".*Total length of survey legs = \s*(\S+)m") en_lengthre = re.compile(r".*Total length of survey legs = \s*(\S+)m")
en_depthre = re.compile(r".*Vertical range =\s*(\S+)m") en_depthre = re.compile(r".*Vertical range =\s*(\S+)m")
def get_stats_from_log(log): def get_stats_from_log(log):
lenmatch = fr_lengthre.findall(log) lenmatch = fr_lengthre.findall(log)
depmatch = fr_depthre.findall(log) depmatch = fr_depthre.findall(log)
if len(lenmatch) == 0 and len(depmatch) == 0: if len(lenmatch) == 0 and len(depmatch) == 0:
lenmatch = en_lengthre.findall(log) lenmatch = en_lengthre.findall(log)
depmatch = en_depthre.findall(log) depmatch = en_depthre.findall(log)
if len(lenmatch) == 1 and len(depmatch) == 1: if len(lenmatch) == 1 and len(depmatch) == 1:
return {"length": lenmatch[0], "depth": depmatch[0]} return {"length": lenmatch[0], "depth": depmatch[0]}
return {"length": 0.0, "depth": 0.0} return {"length": 0.0, "depth": 0.0}
################################################################################################# #################################################################################################
syscoord = re.compile(r".*output coordinate system: \s*(\S+)") syscoord = re.compile(r".*output coordinate system: \s*(\S+)")
def get_syscoord_from_log(log): def get_syscoord_from_log(log):
lenmatch = syscoord.findall(log) lenmatch = syscoord.findall(log)
if len(lenmatch) == 1: if len(lenmatch) == 1:
return {"syscoord": lenmatch[0]} return {"syscoord": lenmatch[0]}
return {"syscoord": 0} return {"syscoord": 0}
+37 -106
View File
@@ -1,92 +1,35 @@
""" """
!---------------------------------------------------------! !---------------------------------------------------------!
! ! ! !
! TroX to Therion ! ! TroX to Therion !
! ! ! !
! Code to transform the .troX files ! ! Code to transform the .troX files !
! Visual Topo into files that can ! ! Visual Topo into files that can !
! be used by Therion ! ! be used by Therion !
! ! ! !
! Written by Alexandre Pont ! ! Written by Alexandre Pont !
! ! ! !
!---------------------------------------------------------! !---------------------------------------------------------!
ENGLISH : ENGLISH :
This code is to transform the .trox file from Visualtopo (http://vtopo.free.fr/) This code is to transform the .trox file from Visualtopo (http://vtopo.free.fr/)
into files that can be read by Therion (http://therion.speleo.sk/). into files that can be read by Therion (http://therion.speleo.sk/).
It reads .tro file and produce one .th file (file with survey data), It reads .tro file and produce one .th file (file with survey data),
and one thconfig file (file that is used to compile and build the survey with Therion). and one thconfig file (file that is used to compile and build the survey with Therion).
Création Alex 2026 01 08
Création Alex 2026 01 08
TODOS : -....
TODOS : -....
""" """
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET # noqa: I001
from collections import defaultdict, Counter from collections import defaultdict, Counter
from pathlib import Path from pathlib import Path
from Lib.general_fonctions import Colors, safe_relpath from Lib.general_fonctions import Colors
import Lib.global_data as global_data
def analyse_xml_balises_old(xml_path):
"""
Analyse un fichier XML et affiche :
- le nombre d'occurrences de chaque balise
- pour chaque balise, les attributs rencontrés et leurs occurrences
Parameters
----------
xml_path : str | Path
Chemin vers le fichier XML
"""
xml_path = Path(xml_path)
if not xml_path.exists():
raise FileNotFoundError(f"{Colors.ERROR}Fichier introuvable : {Colors.ENDC}{xml_path}")
# Chargement XML
tree = ET.parse(xml_path)
root = tree.getroot()
# Comptage des balises
tag_counter = Counter()
# Dictionnaire :
# { tag_name : Counter({attr_name: nb_occurrences}) }
attributes_counter = defaultdict(Counter)
# Parcours de tous les éléments
for elem in root.iter():
tag_counter[elem.tag] += 1
for attr_name in elem.attrib.keys():
attributes_counter[elem.tag][attr_name] += 1
# Affichage
print("\n")
print("=" * 80)
print(f"{Colors.INFO}Analyse du fichier : {Colors.ENDC}{xml_path.name}")
print("=" * 80)
for tag in sorted(tag_counter.keys()):
print(f"\n{Colors.BLUE}Balise <{Colors.ENDC}{tag}{Colors.BLUE}>")
print(f" {Colors.CYAN}Occurrences : {Colors.ENDC}{tag_counter[tag]}")
if attributes_counter[tag]:
print(f" {Colors.MAGENTA}Attributs :")
for attr, count in attributes_counter[tag].most_common():
print(f" {Colors.MAGENTA}- {Colors.ENDC}{attr}{Colors.MAGENTA} : {Colors.ENDC}{count}")
else:
print(f" {Colors.RED}Attributs : aucun")
print(f"\n{Colors.INFO}Analyse terminée.")
#################################################################################################
def analyse_xml_balises(xml_path): def analyse_xml_balises(xml_path):
""" """
Analyse un fichier XML et affiche : Analyse un fichier XML et affiche :
@@ -98,23 +41,15 @@ def analyse_xml_balises(xml_path):
xml_path = Path(xml_path) xml_path = Path(xml_path)
if not xml_path.exists(): if not xml_path.exists():
raise FileNotFoundError( raise FileNotFoundError(f"{Colors.ERROR}Fichier introuvable : {Colors.ENDC}{xml_path}")
f"{Colors.ERROR}Fichier introuvable : {Colors.ENDC}{xml_path}"
)
# ---------------------------- # ----------------------------
# Définition des catégories # Définition des catégories
# ---------------------------- # ----------------------------
TAG_CATEGORIES = { TAG_CATEGORIES = {
"Version": { "Version": {"version", "header", "metadata"},
"version", "header", "metadata" "Mesures": {"mesure", "measure", "value", "data", "record"},
}, "Param": {"param", "parameter", "config", "setting"},
"Mesures": {
"mesure", "measure", "value", "data", "record"
},
"Param": {
"param", "parameter", "config", "setting"
},
} }
DEFAULT_CATEGORY = "Autres" DEFAULT_CATEGORY = "Autres"
@@ -159,26 +94,22 @@ def analyse_xml_balises(xml_path):
# ---------------------------- # ----------------------------
# Affichage # Affichage
# ---------------------------- # ----------------------------
print("\n" + "=" * 80) print(f"{Colors.INFO}" + "=" * 80)
print(f"{Colors.INFO}Analyse du fichier : {Colors.ENDC}{xml_path.name}") print(f"{Colors.INFO}Analyse du fichier : {Colors.ENDC}{xml_path.name}")
print("=" * 80) print(f"{Colors.INFO}" + "=" * 80)
for category in sorted(categorized_tags.keys()): for category in sorted(categorized_tags.keys()):
print(f"\n{Colors.YELLOW}## {category}{Colors.ENDC}") print(f"{Colors.YELLOW}## {category}{Colors.ENDC}")
print("-" * 60) print(f"{Colors.INFO}" + "-" * 60)
for tag in sorted(categorized_tags[category]): for tag in sorted(categorized_tags[category]):
print(f"\n {Colors.BLUE}Balise <{Colors.ENDC}{tag}{Colors.BLUE}>") print(f"{Colors.BLUE}Balise <{Colors.ENDC}{tag}{Colors.BLUE}>\t{Colors.CYAN}Occurrences : {Colors.ENDC}{tag_counter[tag]}")
print(f" {Colors.CYAN}Occurrences : {Colors.ENDC}{tag_counter[tag]}")
if attributes_counter[tag]: if attributes_counter[tag]:
print(f" {Colors.MAGENTA}Attributs :{Colors.ENDC}") print(f"\t{Colors.MAGENTA}Attributs :{Colors.ENDC}")
for attr, count in attributes_counter[tag].most_common(): for attr, count in attributes_counter[tag].most_common():
print( print(f"\t\t{Colors.MAGENTA}- {Colors.ENDC}{attr}{Colors.MAGENTA} : {Colors.ENDC}{count}")
f" {Colors.MAGENTA}- {Colors.ENDC}{attr}" # else:
f"{Colors.MAGENTA} : {Colors.ENDC}{count}" # print(f"\t{Colors.RED}Attributs : aucun{Colors.ENDC}")
)
else:
print(f" {Colors.RED}Attributs : aucun{Colors.ENDC}")
print(f"\n{Colors.INFO}Analyse terminée.{Colors.ENDC}") print(f"{Colors.INFO}Analyse terminée.{Colors.ENDC}")
File diff suppressed because it is too large. Load diff
@@ -25,6 +25,7 @@
"etrs", "etrs",
"european", "european",
"fnme", "fnme",
"FURB",
"geocentricdatumofaustralia", "geocentricdatumofaustralia",
"geocentricofaustralia", "geocentricofaustralia",
"icomments", "icomments",