From 7f93cb851181e6080fd8c5dda58672d2e461a093 Mon Sep 17 00:00:00 2001 From: Alex38Lyon <55714436+Alex38Lyon@users.noreply.github.com> Date: Fri, 9 Jan 2026 11:31:48 +0100 Subject: [PATCH] pyThStat update --- .../database_Synthese-PSM_LARRA_histo.pdf | Bin 12007 -> 12007 bytes .../database_Synthese-PSM_LARRA_log.log | 93 ++++ .../database_Synthese-PSM_LARRA_rose.pdf | Bin 17464 -> 17464 bytes .../database_Synthese-PSM_LARRA_stats.csv | 22 +- .../database_Synthese-PSM_LARRA_stats.db | Bin .../database_Synthese-PSM_LARRA_stats.md | 20 +- .../database_Synthese-PSM_LARRA_year.pdf | Bin 13142 -> 13142 bytes .../database_Synthese-PSM_LARRA_yearCum.pdf | Bin 14625 -> 14625 bytes Scripts/pyThStat/.vscode/settings.json | 5 + .../general_fonctions.cpython-314.pyc | Bin 0 -> 9605 bytes .../__pycache__/global_data.cpython-314.pyc | Bin 0 -> 548 bytes Scripts/pyThStat/Lib/general_fonctions.py | 239 +++++++++ Scripts/pyThStat/Lib/global_data.py | 14 + .../pyThStat/pythStat-VSCode.code-workspace | 7 +- Scripts/pyThStat/pythStat.py | 459 ++++++++---------- Synthese-PSM_LARRA.thconfig | 2 +- 16 files changed, 577 insertions(+), 284 deletions(-) rename Outputs/{stat_database_Synthese-PSM_LARRA_2026-01-08 => Stats_database_Synthese-PSM_LARRA_2026-01-09}/database_Synthese-PSM_LARRA_histo.pdf (99%) create mode 100644 Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_log.log rename Outputs/{stat_database_Synthese-PSM_LARRA_2026-01-08 => Stats_database_Synthese-PSM_LARRA_2026-01-09}/database_Synthese-PSM_LARRA_rose.pdf (99%) rename Outputs/{stat_database_Synthese-PSM_LARRA_2026-01-08 => Stats_database_Synthese-PSM_LARRA_2026-01-09}/database_Synthese-PSM_LARRA_stats.csv (97%) rename Outputs/{stat_database_Synthese-PSM_LARRA_2026-01-08 => Stats_database_Synthese-PSM_LARRA_2026-01-09}/database_Synthese-PSM_LARRA_stats.db (100%) rename Outputs/{stat_database_Synthese-PSM_LARRA_2026-01-08 => Stats_database_Synthese-PSM_LARRA_2026-01-09}/database_Synthese-PSM_LARRA_stats.md (98%) rename Outputs/{stat_database_Synthese-PSM_LARRA_2026-01-08 => Stats_database_Synthese-PSM_LARRA_2026-01-09}/database_Synthese-PSM_LARRA_year.pdf (99%) rename Outputs/{stat_database_Synthese-PSM_LARRA_2026-01-08 => Stats_database_Synthese-PSM_LARRA_2026-01-09}/database_Synthese-PSM_LARRA_yearCum.pdf (99%) create mode 100644 Scripts/pyThStat/Lib/__pycache__/general_fonctions.cpython-314.pyc create mode 100644 Scripts/pyThStat/Lib/__pycache__/global_data.cpython-314.pyc create mode 100644 Scripts/pyThStat/Lib/general_fonctions.py create mode 100644 Scripts/pyThStat/Lib/global_data.py diff --git a/Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_histo.pdf b/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_histo.pdf similarity index 99% rename from Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_histo.pdf rename to Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_histo.pdf index e8c7f5b729af1900ad921503ac2c0784769c9128..60058aeef155014a174031a8f096817d3abf1e31 100644 GIT binary patch delta 20 bcmaDJ`#g4osW!W%p`nqvq2Xp5?bXZxQ!@t6 delta 20 bcmaDJ`#g4osW!WXk+F%nvC(E5?bXZxQ)~v+ diff --git a/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_log.log b/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_log.log new file mode 100644 index 0000000..61aa4e7 --- /dev/null +++ b/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_log.log @@ -0,0 +1,93 @@ +2026-01-09 09:45:02,910 - INFO - ************************************************************************************************************************* +2026-01-09 09:45:02,911 - INFO - * Calcul des statistiques par entrées d'une BD Therion * +2026-01-09 09:45:02,911 - INFO - * Script pythStat par : alexandre.pont@yahoo.fr * +2026-01-09 09:45:02,911 - INFO - * Version : 2026.01.09 * +2026-01-09 09:45:02,911 - INFO - * Fichier source : ~\Synthese-PSM_LARRA\Outputs\database_Synthese-PSM_LARRA.sql * +2026-01-09 09:45:02,913 - INFO - * Dossier destination : ~\Synthese-PSM_LARRA\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09 * +2026-01-09 09:45:02,913 - INFO - * Date : 2026-01-09 09:44:59 * +2026-01-09 09:45:02,913 - INFO - * * +2026-01-09 09:45:02,913 - INFO - ************************************************************************************************************************* +2026-01-09 09:45:02,914 - INFO - Phase 5: Écriture des statistiques dans fichier ~\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09\database_Synthese-PSM_LARRA_stats +2026-01-09 09:46:26,234 - INFO - Table des STATION, entrée et fix nbre: 193 +2026-01-09 09:47:41,830 - INFO - Phase 6: Fin de traitement en 02(m)42(s), résultats enregistrés dans ~\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09\database_Synthese-PSM_LARRA_stats +2026-01-09 10:19:59,707 - INFO - *********************************************************************************************************************** +2026-01-09 10:19:59,707 - INFO - * Calcul des statistiques par entrées d'une BD Therion * +2026-01-09 10:19:59,708 - INFO - * Script pythStat par : alexandre.pont@yahoo.fr * +2026-01-09 10:19:59,708 - INFO - * Version : 2026.01.09 * +2026-01-09 10:19:59,708 - INFO - * Fichier source : ~\Synthese-PSM_LARRA\Outputs\database_Synthese-PSM_LARRA.sql * +2026-01-09 10:19:59,708 - INFO - * Dossier destination : ~\Synthese-PSM_LARRA\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09 * +2026-01-09 10:19:59,708 - INFO - * Date : 2026-01-09 10:19:46 * +2026-01-09 10:19:59,709 - INFO - * * +2026-01-09 10:19:59,709 - INFO - *********************************************************************************************************************** +2026-01-09 10:19:59,710 - INFO - Phase 5: Écriture des statistiques dans fichier ~\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09\database_Synthese-PSM_LARRA_stats +2026-01-09 10:21:21,576 - INFO - Table des STATION, entrée et fix nbre: 193 +2026-01-09 10:22:30,700 - INFO - Phase 6: Fin de traitement en 02(m)43(s), résultats enregistrés dans ~\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09\database_Synthese-PSM_LARRA_stats +2026-01-09 10:24:45,769 - INFO - *********************************************************************************************************************** +2026-01-09 10:24:45,770 - INFO - * Calcul des statistiques par entrées d'une BD Therion * +2026-01-09 10:24:45,770 - INFO - * Script pythStat par : alexandre.pont@yahoo.fr * +2026-01-09 10:24:45,770 - INFO - * Version : 2026.01.09 * +2026-01-09 10:24:45,770 - INFO - * Fichier source : ~\Synthese-PSM_LARRA\Outputs\database_Synthese-PSM_LARRA.sql * +2026-01-09 10:24:45,770 - INFO - * Dossier destination : ~\Synthese-PSM_LARRA\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09 * +2026-01-09 10:24:45,771 - INFO - * Date : 2026-01-09 10:24:42 * +2026-01-09 10:24:45,771 - INFO - * * +2026-01-09 10:24:45,771 - INFO - *********************************************************************************************************************** +2026-01-09 10:24:45,772 - INFO - Phase 1: Importation de la base de données Therion ~\Synthese-PSM_LARRA\Outputs\database_Synthese-PSM_LARRA.sql dans: ~\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09\database_Synthese-PSM_LARRA_stats.db +2026-01-09 11:02:25,463 - INFO - Phase 2: Création des nouvelles tables, indexation +2026-01-09 11:02:26,776 - INFO - Jonction de SHOT equates nbre: 2572 +2026-01-09 11:04:43,650 - WARNING - Table des SHOT, visée(s) bloquante(s), même départ et arrivée, longueur nulle supprimée(s) nbre: 1688 +2026-01-09 11:04:43,863 - WARNING - Table des SHOT, visées en double à traiter à la source : [(1637, None, 2.77)], [(1647, None, 2.77)], station crée : 67391, long. en double : 2.77 m +2026-01-09 11:04:44,056 - WARNING - Table des SHOT, visées en double à traiter à la source : [(9824, 'srf', 8.76)], [(14684, 'srf', 8.73)], station crée : 67394, long. en double : 11.50 m +2026-01-09 11:04:44,423 - WARNING - Table des SHOT, visées en double à traiter à la source : [(51351, None, 17.6)], [(51469, None, 18.0)], station crée : 67400, long. en double : 29.50 m +2026-01-09 11:04:44,482 - WARNING - Table des SHOT, visées en double à traiter à la source : [(51407, None, 6.5)], [(51441, None, 10.0)], station crée : 67401, long. en double : 39.50 m +2026-01-09 11:04:44,495 - INFO - Table des SHOT, visées dupliquées traités nbre: 11 +2026-01-09 11:04:44,843 - INFO - Création de l'index des tables principales et optimisation de la mémoire +2026-01-09 11:04:45,006 - INFO - Marquage des visées et des stations d'habillage nbre: 19045 +2026-01-09 11:05:54,650 - INFO - Table des STATION, entrée et fix nbre: 193 +2026-01-09 11:05:54,654 - INFO - Phase 3: Remplissage des tables d'après les 193 entrée(s) +2026-01-09 11:05:57,725 - INFO - Phase 4: Remplissage des tables d'après les séries vides jonctionnées aux 193 entrée(s) +on 1423: 2026-01-09 11:06:16,743 - INFO - Jonction à la Station_ID: 49336 entre les entrées 49457 et 49328 +on 3315: 2026-01-09 11:06:37,223 - INFO - Jonction à la Station_ID: 229 entre les entrées 218 et 834 +on 3343: 2026-01-09 11:06:37,890 - INFO - Jonction à la Station_ID: 3525 entre les entrées 3455 et 3525 +on 6314: 2026-01-09 11:07:11,828 - INFO - Jonction à la Station_ID: 1666 entre les entrées 1613 et 2784 +on 9044: 2026-01-09 11:08:18,581 - INFO - Jonction à la Station_ID: 3348 entre les entrées 3358 et 3397 +on 9999: 2026-01-09 11:08:44,186 - INFO - Jonction à la Station_ID: 40146 entre les entrées 38328 et 39667 +on 12262: 2026-01-09 11:09:32,307 - INFO - Jonction à la Station_ID: 47397 entre les entrées 48105 et 47361 +on 12737: 2026-01-09 11:09:40,587 - INFO - Jonction à la Station_ID: 9041 entre les entrées 10902 et 8905 +on 15193: 2026-01-09 11:10:39,570 - INFO - Jonction à la Station_ID: 12059 entre les entrées 10902 et 12987 +on 16399: 2026-01-09 11:11:02,917 - INFO - Jonction à la Station_ID: 9337 entre les entrées 14852 et 10902 +on 16399: 2026-01-09 11:11:02,925 - INFO - Jonction à la Station_ID: 9337 entre les entrées 14852 et 10902 +on 16453: 2026-01-09 11:11:04,608 - INFO - Jonction à la Station_ID: 9547 entre les entrées 9884 et 9366 +on 17153: 2026-01-09 11:11:24,074 - INFO - Jonction à la Station_ID: 49863 entre les entrées 48105 et 49804 +on 17700: 2026-01-09 11:11:34,566 - INFO - Jonction à la Station_ID: 12777 entre les entrées 10902 et 14852 +on 17701: 2026-01-09 11:11:34,763 - INFO - Jonction à la Station_ID: 9338 entre les entrées 10902 et 14852 +on 17701: 2026-01-09 11:11:34,805 - INFO - Jonction à la Station_ID: 12777 entre les entrées 10902 et 14852 +on 18840: 2026-01-09 11:12:56,589 - INFO - Jonction à la Station_ID: 12771 entre les entrées 14852 et 9366 +on 18914: 2026-01-09 11:12:59,081 - INFO - Jonction à la Station_ID: 17222 entre les entrées 16774 et 10902 +on 21020: 2026-01-09 11:14:16,661 - INFO - Jonction à la Station_ID: 15570 entre les entrées 8905 et 9366 +on 23018: 2026-01-09 11:15:08,149 - INFO - Jonction à la Station_ID: 15611 entre les entrées 9366 et 8905 +on 23099: 2026-01-09 11:15:11,736 - INFO - Jonction à la Station_ID: 15557 entre les entrées 8905 et 9366 +on 23104: 2026-01-09 11:15:11,799 - INFO - Jonction à la Station_ID: 9477 entre les entrées 8905 et 14852 +on 23106: 2026-01-09 11:15:12,005 - INFO - Jonction à la Station_ID: 9834 entre les entrées 14852 et 11338 +on 23950: 2026-01-09 11:15:35,190 - INFO - Jonction à la Station_ID: 47028 entre les entrées 49090 et 48105 +on 24942: 2026-01-09 11:15:56,520 - INFO - Jonction à la Station_ID: 16242 entre les entrées 15665 et 14852 +on 25665: 2026-01-09 11:16:17,092 - INFO - Jonction à la Station_ID: 16259 entre les entrées 10902 et 14852 +on 28197: 2026-01-09 11:17:13,274 - INFO - Jonction à la Station_ID: 9522 entre les entrées 16789 et 9366 +on 28370: 2026-01-09 11:17:19,650 - INFO - Jonction à la Station_ID: 44663 entre les entrées 49457 et 43629 +on 29811: 2026-01-09 11:17:52,590 - INFO - Jonction à la Station_ID: 44815 entre les entrées 48105 et 49457 +on 30890: 2026-01-09 11:18:15,149 - INFO - Jonction à la Station_ID: 16483 entre les entrées 15665 et 10902 +on 31336: 2026-01-09 11:18:28,033 - INFO - Jonction à la Station_ID: 17453 entre les entrées 19538 et 17667 +on 31834: 2026-01-09 11:18:37,801 - INFO - Jonction à la Station_ID: 25261 entre les entrées 27454 et 24729 +2026-01-09 11:23:00,092 - INFO - Intégrations des visées orphelines (entre 2 stations existantes) nbre: 338 +2026-01-09 11:23:04,529 - INFO - Réseau: 1, entrées jonctionnées: 10, [11338, 14852, 8905, 9366, 10902, 15665, 9884, 16789, 12987, 16774] +2026-01-09 11:23:04,611 - INFO - Réseau: 2, entrées jonctionnées: 2, [3397, 3358] +2026-01-09 11:23:04,914 - INFO - Réseau: 3, entrées jonctionnées: 7, [43629, 49457, 48105, 49328, 47361, 49090, 49804] +2026-01-09 11:23:04,995 - INFO - Réseau: 4, entrées jonctionnées: 2, [1613, 2784] +2026-01-09 11:23:05,087 - INFO - Réseau: 5, entrées jonctionnées: 2, [3455, 3525] +2026-01-09 11:23:05,236 - INFO - Réseau: 6, entrées jonctionnées: 2, [24729, 27454] +2026-01-09 11:23:05,388 - INFO - Réseau: 7, entrées jonctionnées: 2, [834, 218] +2026-01-09 11:23:05,486 - INFO - Réseau: 8, entrées jonctionnées: 2, [38328, 39667] +2026-01-09 11:23:05,589 - INFO - Réseau: 9, entrées jonctionnées: 2, [17667, 19538] +2026-01-09 11:23:05,590 - WARNING - Phase 4: Fin du remplissage des tables, attention 82 station(s) non comptabilisé(s) +2026-01-09 11:23:05,713 - INFO - Phase 5: Écriture des statistiques dans fichier ~\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09\database_Synthese-PSM_LARRA_stats +2026-01-09 11:25:20,502 - INFO - Table des STATION, entrée et fix nbre: 193 +2026-01-09 11:27:11,770 - WARNING - Phase 6: Fin de traitement en 01(h)02(m)28(s), avec 1 erreur(s), résultats enregistrés dans ~\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09\database_Synthese-PSM_LARRA_stats diff --git a/Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_rose.pdf b/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_rose.pdf similarity index 99% rename from Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_rose.pdf rename to Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_rose.pdf index 1c5171a30ab9d8931188ccab37003e9645fe0c01..2e0e06a981d70f7362102d29ee3726420ecd1982 100644 GIT binary patch delta 22 dcmdnd!MLM?aYL6QyQQI_k-4G4=82BWnE+kl2bcf= delta 22 dcmdnd!MLM?aYL6QyM>XliMg@i=82BWnE+lJ2cG}{ diff --git a/Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_stats.csv b/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_stats.csv similarity index 97% rename from Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_stats.csv rename to Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_stats.csv index e60b424..4702707 100644 --- a/Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_stats.csv +++ b/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_stats.csv @@ -1,13 +1,13 @@ -************************************************************************************************************************* -* Calcul des statistiques par entrées d'une BD Therion * -* Script pythStat par alexandre.pont@yahoo.fr * -* Version : 2026.01.09 * -* Fichier source : ~\Synthese-PSM_LARRA\Outputs\database_Synthese-PSM_LARRA.sql * -* Dossier destination : ~\Synthese-PSM_LARRA\Outputs\stat_database_Synthese-PSM_LARRA_2026-01-08 * -* Date : 2026-01-08 23:45:03 * -* Durée calcul: 02(m)28(s) sans erreur * -************************************************************************************************************************* -**Développement total centerline:** 340754.54 13027.78 10574.75 - - Dev.(m), Dupl.(m), Surf.(m) +*********************************************************************************************************************** +* Calcul des statistiques par entrées d'une BD Therion * +* Script pythStat par : alexandre.pont@yahoo.fr * +* Version : 2026.01.09 * +* Fichier source : ~\Synthese-PSM_LARRA\Outputs\database_Synthese-PSM_LARRA.sql * +* Dossier destination : ~\Synthese-PSM_LARRA\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09 * +* Date : 2026-01-09 10:24:42 * +* Durée calcul : 01(h)02(m)28(s) avec erreur(s): 1 * +*********************************************************************************************************************** +**Développement total centerline (m):** développement: 340754.54 , dupliqué: 13027.78 , surface: 10574.75 Attention, 82 station(s) non comptabilisée(s) et raccordée(s) Développement total par réseaux @@ -179,7 +179,7 @@ Développement total par réseaux UT683_4758 1 0.00 0.00 0.00 20.00 2 LT346_80 2000.00 LT346_80 2000.00 Entrée(s) sans topographie 8 0.00 537.00 0.00 0.00 0 LT345_79 1500.0 SC_3 2037.00 -Développement total topographié par année(s)** +Développement total topographié par année(s) Année Dev.(m) Cumul (m) Dupl.(m) Cumul (m) Surf.(m) Cumul (m) 1950 1724.74 1724.74 0.00 0.00 0.00 0.00 1971 2627.02 4351.76 116.43 116.43 0.00 0.00 diff --git a/Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_stats.db b/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_stats.db similarity index 100% rename from Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_stats.db rename to Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_stats.db diff --git a/Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_stats.md b/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_stats.md similarity index 98% rename from Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_stats.md rename to Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_stats.md index db0c27e..ecf1c3a 100644 --- a/Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_stats.md +++ b/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_stats.md @@ -1,14 +1,16 @@ -------------- # Calcul des statistiques par entrées d'une BD Therion -- ** Script pythStat par alexandre.pont@yahoo.fr** -- ** Version : 2026.01.09** -- ** Fichier source : ~\Synthese-PSM_LARRA\Outputs\database_Synthese-PSM_LARRA.sql** -- ** Dossier destination : ~\Synthese-PSM_LARRA\Outputs\stat_database_Synthese-PSM_LARRA_2026-01-08** -- ** Date : 2026-01-08 23:45:03** -- ** Durée calcul : 02(m)28(s) sans erreur** +- Script pythStat par : alexandre.pont@yahoo.fr +- Version : 2026.01.09 +- Fichier source : ~\Synthese-PSM_LARRA\Outputs\database_Synthese-PSM_LARRA.sql +- Dossier destination : ~\Synthese-PSM_LARRA\Outputs\Stats_database_Synthese-PSM_LARRA_2026-01-09 +- Date : 2026-01-09 10:24:42 +- Durée calcul : 01(h)02(m)28(s)!! avec erreur(s): 1 -------------- -**Développement total des centerlines (m):** , Développement: '340754.54', Dupliqué: '13027.78', Surface: '10574.75' -!!Attention, 82 station(s) non comptabilisée(s) et raccordée(s) + +**Développement total des centerlines (m):** développement: `340754.54`, dupliqué: `13027.78`, surface: `10574.75` +!!Attention, `82` station(s) non comptabilisée(s) et raccordée(s) + -------------- **Développement total par réseaux** @@ -239,3 +241,5 @@ | 2023 | 6343.27 | 327354.72 | 1180.34 | 12377.13 | 79.70 | 10279.50 | | 2024 | 7703.88 | 335058.60 | 547.76 | 12924.89 | 144.72 | 10424.22 | | 2025 | 5695.94 | 340754.54 | 102.89 | 13027.78 | 150.53 | 10574.75 | + +-------------- diff --git a/Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_year.pdf b/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_year.pdf similarity index 99% rename from Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_year.pdf rename to Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_year.pdf index ffe5b894bd812ff6f92a21ba46bdc352f2698410..53cbf850e7539e766dbb0f5cf612514b041e5c62 100644 GIT binary patch delta 20 bcmcbXb}el~jXt}jp`nqvfyL%#{maY%SM3La delta 20 bcmcbXb}el~jXt}Dk+F%nvBBnM{maY%SN8{j diff --git a/Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_yearCum.pdf b/Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_yearCum.pdf similarity index 99% rename from Outputs/stat_database_Synthese-PSM_LARRA_2026-01-08/database_Synthese-PSM_LARRA_yearCum.pdf rename to Outputs/Stats_database_Synthese-PSM_LARRA_2026-01-09/database_Synthese-PSM_LARRA_yearCum.pdf index da8956aacd84602ec1514355d61519b4d087e465..656639ea9d7869e6f9f4fb738f2c6d7086a3e61e 100644 GIT binary patch delta 20 bcmZ2jw6JKycN2C?Lqj8T1Ix|-Oq5vwS=OkN diff --git a/Scripts/pyThStat/.vscode/settings.json b/Scripts/pyThStat/.vscode/settings.json index 8fe6e81..eb614e3 100644 --- a/Scripts/pyThStat/.vscode/settings.json +++ b/Scripts/pyThStat/.vscode/settings.json @@ -2,15 +2,18 @@ "cSpell.words": [ "annee", "annees", + "ansi", "arrivee", "axhline", "barplot", + "centerlines", "CENTRELINE", "Criou", "cumsum", "dupl", "Dupl", "duree", + "ENDC", "entetes", "executemany", "Explo", @@ -38,12 +41,14 @@ "results", "serie", "Serie", + "sinfo", "sommeplot", "sommesys", "Sornin", "sqlite", "suprimmees", "tempplot", + "thconfig", "therion", "topographié", "topographiée", diff --git a/Scripts/pyThStat/Lib/__pycache__/general_fonctions.cpython-314.pyc b/Scripts/pyThStat/Lib/__pycache__/general_fonctions.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f609fd346019a60e30a2002c12e525ca16876525 GIT binary patch literal 9605 zcmcIJTWlLwb~EH~_!cRN5-m%zMw0cQY{@UJV#`iqMWP zEf@i_+fAgTT~lca$!LJ6#TIK92J93IY>LfCP;WOWP+%!j1&IrF6QBzO>6dqY;5!h?y3Y1;ma==I2G}D^30EiQW*Y zj%KUxWve5hue9~EM^2uA22($KIOHq6syUsbw$H<8oVq|MG-$T!;yy*q(+b0@6b-Ld zSe{X|yhhRStfJ?&iht%x0r z1S68Xh!=V|BxymOqyaz%j)f!!53u=xz7QFIBD9!Yd~Zn7V;t<@NC?B;&@Bp1LDIpf zqZaAB-mnl7y&SO%6{X-5@{a8XFuKM~riFXb>1qjSnIHbCW}MPPDKs|J?>T&&8wn_*u}hwrt6^n9l*R7pnF;Us0M8G2 zW_(g0s>q(`RTt3`&v@XHr<^iLM&L)lK4{2i0lZFSOto=m#$byNW?N=^d^lsQi4SEe z_QXfBEllzmp(A7FIv^okLT71+kA7yf!3+Ydb$>o4wdN)H@;3_xDEwK$8Zz5%Fk*4a zO-+|#F$I*~Y(+(BH$9!Row*@W@w5lu5mKfx$6dt)-l&8EUyNPFL>*PdLXH75b%qf4;!6(w?r-)iAh{g zlsQ3~kA=jrB6ENa3S2NS9~N=j7YT)guwU#k7zU(yx!-^tLsXDtQQ|sb7HReXicFs- z2uD9R4!m(2*!w#Q%zF&HsKlgjj?H8wEE0a0r(uze$-=zYzo?5uiNot(tcgbC0B#Gx z;tGM_AlKc!AO@q0`h2T@k%4|cQUjcH7?2S>Wk^uGm!j;)|QlYe|+o#OVzcc_c%88I5IlxJMLA_iYGC--hR9GPW`R= zo91Ly-?my+$9~S5Uz^Y9s@{2J_1em{M0kDlw)@WPt=XFsNn1ZqXtNZ_iniPBcMjY- zaI-Plcjn)Qe|6?x&wTP^vg6z~MQhnlF_Wbi-*vw?dt-KO;%41X`+j!v{gZdQlY38> z5X`+>`(FKx`Ze?VOko+deJS>d2WCoByTef$L()*c$uw*++BZhOKf3hn>t~2{d&sb1 z2SyCrH85y#$^+eOna%}{`97{8sHELg!2sd8y9%#@FgQ1J8hglHg)b;b6dO_O5qA}y z;WY&gR4JKkwo|_N@lOxH#h=gqua2CU$&_3uyrAQP^k57a!2r3y+U56x_v^z)0Q3(TARx_B5-hA6iz-=b_PBb8jWQr+a`+5{L<2K} zV`GQ~0|~1`bSI*{h;}Si%$|CxzvYm}bM5IaPsfEtwMRa%XqmkzbT1BcpFiAvqQ~2P z0a^XxoDd5t5OZbE*`Y(mSUBK|_(i{<2uKfHLqagHC?Zx2<6*@5MO;gr@P&~IWUA%Z zC8WWNi$cW9W;ZV5+t8l1LzS`+2D`Z^7Q{%W0gIzq`6mG4)J_9cQI|Hi+&8zZ_ucGE znUAK;CpOF{KIr)9c*;DUHqUIBXOgbjl-Uy>21`|8yMA%`;@aSPb;{h9Hg|8ByKnmL z9!r^@h!5`o+IrpnraNhCTbFMRr_9IV!&_zx9!dsBl1#@RTNVZukM(YwC%bs8WuXc>g2ShBwxz`OfWD{} z+dNl}Jk$Af|Lp1R^BzyP_rf*L?Cjz0r!REPa@~gjp6-72f&)N}x!RA8Cl2Mq03PIO0Hh zuh$n8WO!)E_=>cHKaUedk|v>x?7NSrC(HhIK+4Af`~g0jwSLvIVp(T@Qt`JHcU39t zu_et`m3^gSr3bEmRp*j6Q)N%s*X(QhAGfXBlNLu(=OEvbylrmjBr`CQDlovtUc!MM z5ij9;fhu!L^ap&3PYed(oo3DrWxKajk_!{&M=>Gn2Y<-Zr?ZJs{b|1Xe3lmb%9L<8kz!zlie zy9$gJ!uKKy-*tTFk3y6K6lKDC7%h|dgVAznKh+bt_$JDD3hBQYh*w_t9-JtXKQ+)N zW|3)bZsxLDrAG|*`ba}G3F#mvSReyzHZOqGA$cA#5Xs9(CtmS+1K^MmGZzc{KS03K|Lt8SvN=j=qr|(lb2KMd>2+r57*|Fz^FFI?NV3b7X*I zfbS(DOq#%WtdI^?n#S#CF|D4sZZBRP8ss&~bksjgdna^*>=5}j)&)(#}C?U~BzJQ8L! ztu(=mbXDs{RqIZ*!ERVG?$lD&n&r#Oudcn6vUDYNIn~4$P;z5%4zIIRxv^1}F!&M1 zlqh$F=D_bM09ob66c1T-b@=TWhQY?&_D`TPi^ zGjiJ91b4oiUQXkr%&wBxc$ia&a{b^n8cID;8CesSlC_l4UC{Z0q;mS&{FvuJlJJI+c}9^$AvBuBN%*%5#L5Z;-V*Ve$OK#pP7E0YzduKdjM$Xq zC*ltRQ9ZVJILJqOzj!G&?}aX60YF+B=|h3AH*0AtvJ$+xB_Rk9u|!Dw!+Ez4W@3BssFsW>mBW?`EB!0wLdexZ;FpWun*R*rt5x9*X?6> z`fv58YWm`n8Kx@D)Ne5LYh#;C`J#KmSpQ>s%8qy07T;k)3^pxyNis1 zn@lS_9O4t%&=?!Ee8I^AxNOXJJA*f0PkD;LMZpw(Q;<EZIRm6+=@|txJpZ$H2vwr!Uqx@Q<=^%9?y~!%t2b zsLPllSHWyXb)JIJbm_{O#k@(1>L*wawh5#x&@O#m(mdQ42oBXfbX4!b*+NoWDi4=y z79KSD8U91$JmB|Uayr@jfE_U@E`466OGWSyoHbDA-gZFx3(i6B(oeVMX^Ztm%EjbQ ztBESE&JVP3_IjQ zH%u<7dwO~h-Sfr&LUGheI2=F*@k$iDT?}&hI7bdCfLFj>IrFn1&!k95?YrzJQ94pX z#tL52iWq{|fN%wzV+=M=;_V=$5ML3!3OotmloZIP3z8xugIfs3M5iQ0BxHco3qv>` z_CW#*C)-)*ijsm<5g8%uRnlYrf|jUhwUsN6K>+i z3AoU(6vA{2rpvx1{u1}q68QSJp(SIp(~b-H$D)T6=0q=$V1d#)P<)6<-v{M@G`&r& zsoSztCx+fyOk4JESoWtZ?P*KThNUNEIlRO?(5W@HPmiDe3nel7)~jht=Z2*dV)V4- z=!WI!rlt26{*M>_dEwrR>EY)$hM!LjpT|=ullA(E~P$r~rv zx|5bp;K^t;&7T@AfJ;}kY*e+Z_u@3e;FfLATJ?K%H|qXsYT5als)nSg;Y$!-nW?lT zG)tP_Xe$$rcW2Vt=KI>_^}yZcABR3vf8hMN;iGe#$0sw^n#7BVmy*_&B~3S>&I@Z?y$Gm_3q8eLmAtirAy2D2Mip^mZkFg<>kxQuf2I~ z?YRw0Yf{(xhn+#1GS%!*G(OR)MDJTy@9XwFP(%0Y9YYRdgRQ^C;6dBhkd@4mH*Z;O z3D@fRmGdbp_ofD8o4?-KS2E>IBboA*{5*WR?{^G$QU9PFVX1!{FaW&Qs2$l$-D_(H z_zM#Y@Rz2>QHuIySM7*e{jrM1kTs9k)gRZ=81Cgpo>YH)iU#-zWgfMvKe5mNAs?s} zqR}4E>|qBp`31xh)E79-hUixvdy&@b^+$a0^YkhVk)V@AjU+KB;lvQq;u{tWTq61= zNq9&N%t#nYqD~2$Z}KRX@UPI)pJ6bC0r_?M5N@5uU>E?>7s5{xk&^cwiSWoJCNJ>p zGY^||q&t=U$^R+oCUkLRBHsl7=SI`NRq1KwOB+Qy(o|=P>iiFC&u6ST&D!s?_BCCK zZH}uSm?(|ujfvML68#y*_{R8aD6lBWqE`jSng)eN|lZ zrLLOZ`&$aY?+!Q7*58fNO>`$f72UQ|!O&fa%V~S(hP`u#g3eBrg+7oNN!!{sY;8Lf Sbapyx=&JwjJw)5cj{Xmf)|r|B literal 0 HcmV?d00001 diff --git a/Scripts/pyThStat/Lib/__pycache__/global_data.cpython-314.pyc b/Scripts/pyThStat/Lib/__pycache__/global_data.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82955529a10a4f8e7a049a5d10bec7f7dc33e1ed GIT binary patch literal 548 zcmdPqs(~Shp@bobv4k;>p@b=jsf0O*S(!nT zB~ccrj7w3OmOzn$R11jTK!ERguX%*e?2k%^6w<%0kNw|E2l2Mz{) Qfd=jyJc3P}MeINo0I5QADgXcg literal 0 HcmV?d00001 diff --git a/Scripts/pyThStat/Lib/general_fonctions.py b/Scripts/pyThStat/Lib/general_fonctions.py new file mode 100644 index 0000000..86d9b9f --- /dev/null +++ b/Scripts/pyThStat/Lib/general_fonctions.py @@ -0,0 +1,239 @@ +""" +!############################################################################################# +# # +# general_fonctions.py for pythStat.py # +# # +!############################################################################################# + +Alex 2026 01 09 + +""" +import os, logging, sys, re, unicodedata +from pathlib import Path + +log = logging.getLogger("Logger") + +################################################################################################# +# Couleurs ANSI par niveau de log +################################################################################################# +COLOR_CODES = { + logging.DEBUG: "\033[94m", # Bleu + logging.INFO: "\033[92m", # Vert + logging.WARNING: "\033[95m", # MAGENTA + logging.ERROR: "\033[91m", # Rouge + logging.CRITICAL: "\033[1;91m", # Rouge vif +} +RESET = "\033[0m" + +################################################################################################# +# Codes de couleur ANSI +class Colors: + BLACK = '\033[90m' + RED = '\033[91m' + GREEN = '\033[92m' + YELLOW = '\033[93m' + BLUE = '\033[94m' + MAGENTA = '\033[95m' + CYAN = '\033[96m' + WHITE = '\033[97m' + + ERROR = '\033[91m' + WARNING = '\033[95m' + HEADER = '\033[1;94m' + DEBUG = '\033[94m' # Bleu + INFO = '\033[92m' # Vert + CRITICAL = '\033[1;91m', # Rouge vif + + ENDC = '\033[0m' + BOLD = '\033[1m' + UNDERLINE = '\033[4m' + +################################################################################################# +# Coloration des messages d'aide d'arg # +################################################################################################# +def colored_help(parser): + """ + Affiche l'aide colorée pour les arguments de la ligne de commande. + + Args: + parser (argparse.ArgumentParser): Le parseur d'arguments. + Returns: + None + + """ + # Captures the help output + help_text = parser.format_help() + + # Coloration des différentes parties + colored_help_text = help_text.replace( + 'usage:', f'{Colors.ERROR}usage:{Colors.ENDC}' + ).replace( + 'options:', f'{Colors.GREEN}options:{Colors.ENDC}' + ).replace('positional arguments:', f'{Colors.BLUE}positional arguments:{Colors.ENDC}' + ).replace(', --help', f'{Colors.BLUE}, --help:{Colors.ENDC}' + ).replace('elp:', f'{Colors.BLUE}elp{Colors.ENDC}') + + # Surligner les arguments + # for action in parser._actions: + # if action.option_strings: + # # Colorer les options (--xyz) + # 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}') + + # Imprimer le texte coloré + print(colored_help_text) + sys.exit(1) + +################################################################################################# +# Mise au format des noms # +################################################################################################# +def sanitize_filename(thName): + """ + Cleans a string to make it compatible with filenames on Windows, Linux, and macOS. + Replaces special and accented characters with compatible characters. + Replaces parentheses with underscores and enforces proper casing. + + Args: + thName (str): The filename to clean. + + Returns: + str: The cleaned and compatible string. + + """ + # Unicode normalization to replace accented characters with their non-accented equivalents + thName = unicodedata.normalize('NFKD', thName).encode('ASCII', 'ignore').decode('ASCII') + + # Replace parentheses with underscores + thName = thName.replace('(', '_').replace(')', '_') + + # Replace illegal characters with an underscore + thName = re.sub(r'[<>:"/\\|?*\']', '_', thName) # Illegal on Windows + thName = re.sub(r'\s+', '_', thName) # Spaces to underscores + thName = re.sub(r'[^a-zA-Z0-9._-]', '_', thName) # Keep only allowed chars + + # Convert to lowercase, then capitalize the first letter + # thName = thName.lower().capitalize() + # thName = thName.capitalize() + + # Suppression des underscores en début et fin + thName = thName.strip('_') + + return thName or "default_filename" # Avoid empty result + +################################################################################################# +# Supprime les codes ANSI (pour l'écriture dans les fichiers) +################################################################################################# +def strip_ansi_codes(text): + ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') + return ansi_escape.sub('', text) + +################################################################################################# +# Formatter pour la console avec couleurs +################################################################################################# +class ConsoleFormatter(logging.Formatter): + def format(self, record): + color = COLOR_CODES.get(record.levelno, "") + message = super().format(record) + return f"{color}{message}{RESET}" + +################################################################################################# +# Formatter pour le fichier avec "!!!" sur les erreurs +################################################################################################# +class FileFormatter(logging.Formatter): + def format(self, record): + clean_msg = strip_ansi_codes(record.getMessage()) + prefix = "!!! " if record.levelno >= logging.ERROR else "" + record_copy = logging.LogRecord( + name=record.name, + level=record.levelno, + pathname=record.pathname, + lineno=record.lineno, + msg=f"{prefix}{clean_msg}", + args=(), + exc_info=record.exc_info, + func=record.funcName, + sinfo=record.stack_info + ) + return super().format(record_copy) + +################################################################################################# +# Fonction de configuration du logger +################################################################################################# +def setup_logger(logfile="app.log", debug_log=False): + logger = logging.getLogger("Logger") + logger.setLevel(logging.DEBUG) + logger.handlers.clear() + + min_level = logging.DEBUG if debug_log else logging.INFO + + # Console stderr handler — affichage à l'écran avec couleurs + stderr_handler = logging.StreamHandler(sys.stderr) + stderr_handler.setLevel(min_level) + stderr_formatter = ConsoleFormatter("%(levelname)s: %(message)s") # <-- Ta classe personnalisée + stderr_handler.setFormatter(stderr_formatter) + logger.addHandler(stderr_handler) + + # File handler — fichier de log + file_handler = logging.FileHandler(logfile, encoding="utf-8") + file_handler.setLevel(min_level) + file_formatter = FileFormatter("%(asctime)s - %(levelname)s - %(message)s") # <-- Ta classe personnalisée + file_handler.setFormatter(file_formatter) + logger.addHandler(file_handler) + + return logger + +################################################################################################# +# fonction pour réduire l'affichage des chemins long # +################################################################################################# +def safe_relpath(path, base_dir=None, max_depth=3, max_name_len=50, prefix="~"): + """ + Retourne un chemin lisible et sûr pour affichage (logs / UI). + + - Compatible Windows / Linux / macOS + - Tronque la profondeur du chemin + - Tronque le nom de fichier si trop long + - Ne lève jamais d'exception + """ + + try: + path = Path(path).expanduser().resolve() + except Exception: + return str(path) + + try: + base = Path(base_dir).expanduser().resolve() if base_dir else Path.cwd().resolve() + except Exception: + base = None + + name = path.name or str(path) + if len(name) > max_name_len: + stem = path.stem[: max(1, max_name_len - 6)] + name = f"{stem}...{path.suffix}" + + try: + if base: + rel = path.relative_to(base) + parts = list(rel.parts) + else: + raise ValueError + except Exception: + parts = list(path.parts) + + if not parts: + parts = ["."] + + if isinstance(max_depth, int) and max_depth > 0 and len(parts) > max_depth: + parts = parts[-max_depth:] + parts.insert(0, prefix) + + if parts and parts[-1] not in (".", os.sep): + parts[-1] = name + + try: + return os.path.join(*parts) + except Exception: + return name + + + + \ No newline at end of file diff --git a/Scripts/pyThStat/Lib/global_data.py b/Scripts/pyThStat/Lib/global_data.py new file mode 100644 index 0000000..1d083a8 --- /dev/null +++ b/Scripts/pyThStat/Lib/global_data.py @@ -0,0 +1,14 @@ +""" +!#############################################################################################! + +global_data.py for pythStat.py + +!#############################################################################################! +""" + +Version = "2026.01.09" + +################################################################################################# + +error_count = 0 # Compteur d'erreurs +debug_log = False \ No newline at end of file diff --git a/Scripts/pyThStat/pythStat-VSCode.code-workspace b/Scripts/pyThStat/pythStat-VSCode.code-workspace index 876a149..b58d290 100644 --- a/Scripts/pyThStat/pythStat-VSCode.code-workspace +++ b/Scripts/pyThStat/pythStat-VSCode.code-workspace @@ -4,5 +4,10 @@ "path": "." } ], - "settings": {} + "settings": { + "cSpell.words": [ + "ansi", + "ENDC" + ] + } } \ No newline at end of file diff --git a/Scripts/pyThStat/pythStat.py b/Scripts/pyThStat/pythStat.py index 6382332..e31c957 100644 --- a/Scripts/pyThStat/pythStat.py +++ b/Scripts/pyThStat/pythStat.py @@ -1,21 +1,22 @@ # -*- coding: utf-8 -*- - -######################################################################################################################################## +""" +!####################################################################################################################################### # # # Script pour calculer les statistiques des entités jonctionnées # # d'un fichier database (.sql) produit par Therion # # By Alexandre PONT alexandre.pont@yahoo.fr # # # -# Utilisation: # -# Exporter le fichier sql avec therion, commande therion.thconfig : export database -o Outputs/database.sql # -# Commande : python pythStat.py ./chemin/fichier.sql # -# ou : python pythStat.py pour ouvrir une fenêtre # -# Résultat : fichiers dans le dossier crée du fichier source # -######################################################################################################################################## - +* Utilisation: # +# Exporter le fichier sql avec therion, commande therion.thconfig : export database -o Outputs/database.sql # +# Commande : python pythStat.py ./chemin/fichier.sql # +# ou : python pythStat.py pour ouvrir une fenêtre # +# Résultat : fichiers dans le dossier crée du fichier source # +!######################################################################################################################################## +""" import sqlite3, sys, os, re, argparse from pathlib import Path +from os.path import isfile, join, abspath, splitext import numpy as np import pandas as pd import matplotlib.pyplot as plt @@ -24,13 +25,12 @@ from tkinter import filedialog from alive_progress import alive_bar # https://github.com/rsalmei/alive-progress from datetime import datetime -Version ="2026.01.09" +import Lib.global_data as globalDat +from Lib.general_fonctions import setup_logger, Colors, safe_relpath, colored_help - -"""##################################################################################################################################### -# Fonction pour importer un fichier SQL dans une base de données SQLite # -# # -#####################################################################################################################################""" +##################################################################################################################################### +# Fonction pour importer un fichier SQL dans une base de données SQLite # +##################################################################################################################################### def importation_sql_data(fichier_sql): """ Fonction pour importer un fichier SQL dans une base de données SQLite @@ -43,7 +43,7 @@ def importation_sql_data(fichier_sql): try: # Si la base de données existe, supprimez-la pour forcer l'écriture - print(f"\033[1;32mPhase 1: Importation de la base de données Therion \033[0m{safe_relpath(input_file_name)}\033[1;32m dans: \033[0m{safe_relpath(imported_database)}") + log.info(f"Phase 1: Importation de la base de données Therion {Colors.ENDC}{safe_relpath(input_file_name, 2)}{Colors.INFO} dans: {Colors.ENDC}{safe_relpath(imported_database, 0)}") if os.path.exists(imported_database): #print("Suppression de la Bd existante: " + imported_database) os.remove(imported_database) @@ -62,7 +62,7 @@ def importation_sql_data(fichier_sql): # Exécution des commandes avec une barre de progression - with alive_bar(len(commandes), title = "\x1b[32;1m\t Progression\x1b[0m", length = 20) as bar: + with alive_bar(len(commandes), title = f"{Colors.YELLOW}Progression{Colors.ENDC}", length = 20) as bar: for commande in commandes: cursor.execute(commande) connection.commit() @@ -70,7 +70,7 @@ def importation_sql_data(fichier_sql): connection.close() except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête importation_sql_data code:\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête importation_sql_data code:{Colors.ENDC} {e}") error_count += 1 sys.exit(1) # Arrête le programme en cas d'erreur @@ -78,7 +78,6 @@ def importation_sql_data(fichier_sql): ##################################################################################################################################### # Fonction pour construire les tables JONCTION, SERIE, VISEE_FLAG et RESEAU # -# # ##################################################################################################################################### def construction_tables(): """ @@ -90,10 +89,10 @@ def construction_tables(): #conn = sqlite3.connect(database) # Connexion à la base de données SQLite #cursor = conn.cursor() - # print(f"\033[1;32mConstruction des tables dans {imported_database}\033[0m") + # print(f"{Colors.GREEN}{Colors.BOLD}Construction des tables dans {imported_database}{Colors.ENDC}") try : - print(f"\033[1;32mPhase 2: Création des nouvelles tables, indexation\033[0m") + log.info(f"Phase 2: Création des nouvelles tables, indexation") cursor.execute("DROP TABLE IF EXISTS JONCTION") # Créer et initialiser une nouvelle table de jonctions cursor.execute(""" @@ -168,7 +167,7 @@ def construction_tables(): cursor.executemany("INSERT INTO VISEE_FLAG (SHOT_ID) VALUES (?)", results) # type: ignore conn.commit() - print(f"\033[0m\t Création de l'index des tables principales et optimisation de la mémoire\033[0m") + log.info(f"Création de l'index des tables principales et optimisation de la mémoire") cursor.execute("CREATE INDEX INDEX_JONCTION_STATION_ID ON JONCTION(STATION_ID)") cursor.execute("PRAGMA index_list(SHOT)") @@ -190,7 +189,7 @@ def construction_tables(): # A partir des entrées, remplir les tables des jonctions et des séries results = sql_liste_entree() - print(f"\033[1;32mPhase 3: Remplissage des tables d'après les \033[0m{len(results)}\033[1;32m entrée(s)\033[0m") # type: ignore + log.info(f"Phase 3: Remplissage des tables d'après les {Colors.ENDC}{len(results)}{Colors.INFO} entrée(s){Colors.ENDC}") # type: ignore for row in results: # type: ignore # if row[0]==28548: # print("debug point") @@ -234,11 +233,11 @@ def construction_tables(): """) conn.commit() - # print(f"\tCréation Série: {Current_Serie_ID} depuis la station d'entrée Station_ID: {row[0]}") + # print(f"Création Série: {Current_Serie_ID} depuis la station d'entrée Station_ID: {row[0]}") # A partir des série vides, itération pour remplir les tables des JONCTION et des SERIE - print(f"\033[1;32mPhase 4: Remplissage des tables d'après les séries vides jonctionnées aux\033[0m {Current_Serie_ID}\033[1;32m entrée(s)\033[0m") + log.info(f"Phase 4: Remplissage des tables d'après les séries vides jonctionnées aux{Colors.ENDC} {Current_Serie_ID}{Colors.INFO} entrée(s){Colors.ENDC}") results = sql_serie_vides() Count = 1 @@ -252,10 +251,10 @@ def construction_tables(): compteur_ttl = int(_compteur[0][0]) avt_compteur = 0 - with alive_bar(compteur_ttl, title = "\x1b[32;1m\t Progression\x1b[0m", length = 20) as bar: + with alive_bar(compteur_ttl, title = f"{Colors.YELLOW}Progression{Colors.ENDC}", length = 20) as bar: while len(results) > 0: # type: ignore - # print(f"\033[1;32mPhase 4.{Count}: Remplissage des tables JONCTION et SERIE itération: {Count}, séries créée(s): {New_Serie_ID} ajoutée(s): {New_Serie_ID-New_Serie_IDOld} à traiter: {len(results)}\033[0m") # type: ignore - bar.text(f"itération: {Count}, série(s) créée(s): {New_Serie_ID}") # type: ignore + # print(f"{Colors.GREEN}{Colors.BOLD}Phase 4.{Count}: Remplissage des tables JONCTION et SERIE itération: {Count}, séries créée(s): {New_Serie_ID} ajoutée(s): {New_Serie_ID-New_Serie_IDOld} à traiter: {len(results)}{Colors.ENDC}") # type: ignore + bar.text(f"{Colors.YELLOW}itération(s): {Colors.ENDC}{Count}{Colors.YELLOW}, série(s) créée(s): {Colors.ENDC}{New_Serie_ID}") # type: ignore cursor.execute("SELECT COUNT(*) AS nbre FROM JONCTION WHERE STATION_TYPE IS NULL") _compteur = cursor.fetchall() compteur = int(_compteur[0][0]) @@ -274,7 +273,7 @@ def construction_tables(): # Current_Serie_Lenght_Duplicate = 0.0 + float(row[8]) Current_Ent = int(row[10]) Direction = int(row[9]) - #print(f"\tSerie courante {Current_Serie_ID} Station_ID: {Current_Station_ID} results: {results}") + #print(f"Serie courante {Current_Serie_ID} Station_ID: {Current_Station_ID} results: {results}") Fin_Serie = False while Fin_Serie is False: if Direction == 1 : @@ -306,7 +305,7 @@ def construction_tables(): else : # A gérer nouvelles séries nouvelles_series(Current_Station_ID, Current_Station_ID_Old, Current_Serie_ID, 1, Current_Ent) # type: ignore - # print (f"\033[34m\tA traiter création nouvelles séries inverses depuis l'entrée {Current_Station_ID} - {Next_Station_ID_2}, {Next_Station_ID_1}\033[0m") + # print (f"\033[34m\tA traiter création nouvelles séries inverses depuis l'entrée {Current_Station_ID} - {Next_Station_ID_2}, {Next_Station_ID_1}{Colors.ENDC}") nouvelles_series(Current_Station_ID, Current_Station_ID_Old, Current_Serie_ID, -1, Current_Ent) Direction = 1 Next_Station_ID = Next_Station_ID_1 @@ -314,7 +313,7 @@ def construction_tables(): if len(Next_Station_ID) == 0 : # type: ignore Next_Station_ID_1 = sql_station_depart(Current_Station_ID) # type: ignore Next_Station_ID_2 = sql_station_arrivee(Current_Station_ID) # type: ignore - # print(f"\033[34m\tA gérer, fin de la Série: {Current_Serie_ID} à la Station_ID: {Current_Station_ID} nbre: {Current_Nre_Shot} Next station: {Next_Station_ID}, départs directs {len(Next_Station_ID_1)}, départs inverses {len(Next_Station_ID_2)}\033[0m") # type: ignore + # print(f"\033[34m\tA gérer, fin de la Série: {Current_Serie_ID} à la Station_ID: {Current_Station_ID} nbre: {Current_Nre_Shot} Next station: {Next_Station_ID}, départs directs {len(Next_Station_ID_1)}, départs inverses {len(Next_Station_ID_2)}{Colors.ENDC}") # type: ignore # cursor.execute(f"UPDATE SERIE SET SERIE_DEP_ID = {Current_Serie_ID} WHERE SERIE_ID = {Current_Serie_ID};") # type: ignore # cursor.execute(f"UPDATE SERIE SET STATION_DEP_ID = {Current_Station_ID} WHERE SERIE_ID = {Current_Serie_ID};") # type: ignore # cursor.execute(f"UPDATE SERIE SET SERIE_NBRE_SHOT = 0 WHERE SERIE_ID = {Current_Serie_ID};") # type: ignore @@ -337,7 +336,7 @@ def construction_tables(): New_Serie_ID = cursor.lastrowid # type: ignore if resultsOld == results : #print(f"Erreur sortie itération qté: {len(resultsOld)} - {resultsOld} - {results}") - print(f"\033[91mErreur sortie itération {Count}, séries restantes: {len(resultsOld)} - {results}\033[0m") # type: ignore + log.error(f"Erreur sortie itération {Colors.ENDC}{Count}{Colors.ERROR}, séries restantes: {Colors.ENDC}{len(resultsOld)}{Colors.ERROR} - {Colors.ENDC}{results}") # type: ignore error_count += 1 break @@ -357,14 +356,14 @@ def construction_tables(): jonction_RESEAU() if compteur > 0 : - print(f"\033[1;32mPhase 4: Fin du remplissage des tables,\033[91m attention \033[0m{compteur}\033[91m station(s) non comptabilisé(s)\033[0m") + log.warning(f"Phase 4: Fin du remplissage des tables,{Colors.WARNING} attention {Colors.ENDC}{compteur}{Colors.WARNING} station(s) non comptabilisé(s)") error_count += 1 # else : - # print(f"\033[1;32mPhase 4: Fin du remplissage des tables voir {imported_database}\033[0m") + # print(f"{Colors.GREEN}{Colors.BOLD}Phase 4: Fin du remplissage des tables voir {imported_database}{Colors.ENDC}") except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution d'une des requêtes (construction_tables) code:\033[0m {e}") + log.error(f"Erreur lors de l'exécution d'une des requêtes (construction_tables) code:{Colors.ENDC} {e}") error_count += 1 return @@ -407,7 +406,7 @@ def orphelines_shot(): conn.commit() orphelines = cursor.fetchall() - print(f"\t Intégrations des visées orphelines (entre 2 stations existantes) nbre: {len(orphelines)}") + log.info(f"Intégrations des visées orphelines (entre 2 stations existantes) nbre: {Colors.ENDC}{len(orphelines)}") for row in orphelines: _SERIE_LENGHT = 0 @@ -446,12 +445,12 @@ def orphelines_shot(): if row[7] != row[11] : cursor.execute(f"INSERT INTO RESEAU (STATION_JONC, ENT_1, ENT_2) VALUES (?, ?, ?)", (row[8], row[7], row[11])) - # print (f"\033[36m\t Jonction des entrées à la Station_ID: {row[8]} entre: {row[7]} et: {row[11]}\033[0m") + # print (f"{Colors.BLUE}\t Jonction des entrées à la Station_ID: {row[8]} entre: {row[7]} et: {row[11]}{Colors.ENDC}") conn.commit() except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête orphelines_shot code:\033[0m {e}" ) + log.error(f"Erreur lors de l'exécution de la requête orphelines_shot code:{Colors.ENDC} {e}" ) error_count += 1 return @@ -475,7 +474,7 @@ def jonction_RESEAU(): conn.commit() doublons = cursor.fetchall() - # print(f"\t Table des RESEAUX doublons nbre: {len(doublons)}") + # print(f"Table des RESEAUX doublons nbre: {len(doublons)}") for row in doublons : cursor.execute(f"DELETE FROM RESEAU WHERE RESEAU.ID = {row[0]}") conn.commit() @@ -533,7 +532,7 @@ def jonction_RESEAU(): for row2 in jonction: # type: ignore if row2[0] not in liste_entrees_reseau: - # print(f"\t Jonction de l'entrée: {row2[0]} au reseau ID: {index_reseau}") + # print(f"Jonction de l'entrée: {row2[0]} au reseau ID: {index_reseau}") cursor.execute(f"UPDATE RESEAU SET RESEAU_ID = {index_reseau} WHERE RESEAU.ENT_1 = {row2[0]} ") cursor.execute(f"UPDATE RESEAU SET RESEAU_ID = {index_reseau} WHERE RESEAU.ENT_2 = {row2[0]} ") liste_entrees_reseau.append(row2[0]) @@ -545,10 +544,10 @@ def jonction_RESEAU(): cursor.execute(f"UPDATE VISEE_FLAG SET RESEAU_ID = {index_reseau} WHERE VISEE_FLAG.ENTREE_ID = {row2} ") conn.commit() - print(f"\t Réseau: {index_reseau}, entrées jonctionnées: {len(liste_entrees_reseau)}, {liste_entrees_reseau}") + log.info(f"Réseau: {Colors.ENDC}{index_reseau}{Colors.INFO}, entrées jonctionnées: {Colors.ENDC}{len(liste_entrees_reseau)}{Colors.INFO}, {Colors.ENDC}{liste_entrees_reseau}") except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête Jonction_RESEAU code:\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête Jonction_RESEAU code:{Colors.ENDC} {e}") error_count += 1 return @@ -582,7 +581,7 @@ def SHOT_equates_station(): """) equate = cursor.fetchall() - print(f"\t Jonction de SHOT equates nbre: {len(equate)}") + log.info(f"Jonction de SHOT equates nbre: {Colors.ENDC}{len(equate)}") for row in equate : sous_valeurs = row[0].split(',') # print(f": {sous_valeurs[0]} = ", end="") @@ -607,10 +606,10 @@ def SHOT_equates_station(): # print("") - # if len(equate) == 0 : print(f"\tAucun 'equate'") + # if len(equate) == 0 : print(f"Aucun 'equate'") except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête 8 (sql_8_equates) code:\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête 8 (sql_8_equates) code:{Colors.ENDC} {e}") error_count += 1 return @@ -639,6 +638,7 @@ def duplicate_SHOT(): duplicate = cursor.fetchall() _total_length_err = 0.0 + for row in duplicate : sous_valeurs = row[3].split(',') cursor.execute(f""" @@ -665,6 +665,7 @@ def duplicate_SHOT(): shot_flag2 = cursor.fetchall() # print("\t " + str(shot_flag2)) # _total_length += int(row[2]) + if shot_flag[0][1] is None and shot_flag2[0][1]== 'dpl': cursor.execute("SELECT COUNT(*) AS nombre_enregistrements FROM STATION") Current_Station_ID = cursor.fetchall() @@ -672,6 +673,7 @@ def duplicate_SHOT(): cursor.execute(f"INSERT INTO STATION (ID, NAME) VALUES ({_Current_Station_ID}, 'isu')") cursor.execute(f"UPDATE SHOT SET TO_ID = {_Current_Station_ID} WHERE SHOT.ID = {shot_flag2[0][0]}") cursor.execute(f"INSERT INTO JONCTION (STATION_ID) VALUES ({_Current_Station_ID})") + elif shot_flag2[0][1] is None and shot_flag[0][1]== 'dpl': cursor.execute("SELECT COUNT(*) AS nombre_enregistrements FROM STATION") Current_Station_ID = cursor.fetchall() @@ -679,6 +681,7 @@ def duplicate_SHOT(): cursor.execute(f"INSERT INTO STATION (ID, NAME) VALUES ({_Current_Station_ID}, 'isu')") cursor.execute(f"UPDATE SHOT SET TO_ID = {_Current_Station_ID} WHERE SHOT.ID = {shot_flag[0][0]}") cursor.execute(f"INSERT INTO JONCTION (STATION_ID) VALUES ({_Current_Station_ID})") + else : _total_length_err += float(shot_flag2[0][2]) cursor.execute("SELECT COUNT(*) AS nombre_enregistrements FROM STATION") @@ -687,9 +690,9 @@ def duplicate_SHOT(): cursor.execute(f"INSERT INTO STATION (ID, NAME) VALUES ({_Current_Station_ID}, 'isu')") cursor.execute(f"UPDATE SHOT SET TO_ID = {_Current_Station_ID} WHERE SHOT.ID = {shot_flag2[0][0]}") cursor.execute(f"INSERT INTO JONCTION (STATION_ID) VALUES ({_Current_Station_ID})") - print(f"\033[91m\t Table des SHOT, visées en double à traiter à la source : \033[0m{shot_flag}, {shot_flag2}" + - f"\033[91m, station crée : \033[0m{_Current_Station_ID}" + - f"\033[91m, long. en double : \033[0m{"{:.2f}".format(_total_length_err)} m") + log.warning(f"Table des SHOT, visées en double à traiter à la source : {Colors.ENDC}{shot_flag}{Colors.WARNING}, {Colors.ENDC}{shot_flag2}" + + f"{Colors.WARNING}, station crée : {Colors.ENDC}{_Current_Station_ID}" + + f"{Colors.WARNING}, long. en double : {Colors.ENDC}{"{:.2f}".format(_total_length_err)}{Colors.WARNING} m") conn.commit() @@ -699,14 +702,15 @@ def duplicate_SHOT(): # filtre = cursor.fetchall() if len(duplicate) > 0: - print(f"\t Table des SHOT, visées dupliquées traités nbre: {len(duplicate)}") - # print(f"\t Visées dupliqués supprimés {duplicate}") + log.info(f"Table des SHOT, visées dupliquées traités nbre: {Colors.ENDC}{len(duplicate)}") + # print(f"Visées dupliqués supprimés {duplicate}") + else : - print(f"\t Table des SHOT, aucune visée dupliquée") + log.info(f"Table des SHOT, aucune visée dupliquée") except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête (duplicate_SHOT) code:\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête (duplicate_SHOT) code:{Colors.ENDC} {e}") error_count += 1 return @@ -736,14 +740,14 @@ def issue_SHOT(): if len(issue) > 0: - print(f"\t Table des SHOT, visée(s) bloquante(s), même départ et arrivée, longueur nulle supprimée(s) nbre: {len(issue)}") - # print(f"\t Visée(s) bloquante(s) supprimée(s) {issue}") + log.warning(f"Table des SHOT, visée(s) bloquante(s), même départ et arrivée, longueur nulle supprimée(s) nbre: {Colors.ENDC}{len(issue)}") + # print(f"Visée(s) bloquante(s) supprimée(s) {issue}") else : - print(f"\t Table des SHOT, aucune visée bloquante") + log.info(f"Table des SHOT, aucune visée bloquante") except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête (Issue_SHOT) code:\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête (Issue_SHOT) code:{Colors.ENDC} {e}") error_count += 1 return @@ -765,7 +769,7 @@ def marquage_visee_station_habillage() : """ ) filtre = cursor.fetchall() - print(f"\t Marquage des visées et des stations d'habillage nbre: {len(filtre)}") + log.info(f"Marquage des visées et des stations d'habillage nbre: {Colors.ENDC}{len(filtre)}") for row in filtre : cursor.execute(f"UPDATE JONCTION SET STATION_TYPE = 'hab' WHERE STATION_ID = {row[0]}") cursor.execute(f"UPDATE VISEE_FLAG SET SERIE_ID = -1 WHERE SHOT_ID = {row[1]}") @@ -774,7 +778,7 @@ def marquage_visee_station_habillage() : except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête (marquage_station_habillage):\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête (marquage_station_habillage):{Colors.ENDC} {e}") error_count += 1 return @@ -804,7 +808,7 @@ def suivi_serie( _Current_Serie_ID, bar) : _Current_Ent = int(_Serie[0][10]) if _Direction == 0 : - # print(f"\t\033[34mA gérer séries sans direction station série: {_Current_Serie_ID}\033[0m") # type: ignore + # print(f"\033[34mA gérer séries sans direction station série: {_Current_Serie_ID}{Colors.ENDC}") # type: ignore _Current_Station_ID = int(_Serie[0][2]) Next_Station_ID_1 = sql_station_depart(_Current_Station_ID) Next_Station_ID_2 = sql_station_arrivee(_Current_Station_ID) @@ -830,7 +834,7 @@ def suivi_serie( _Current_Serie_ID, bar) : else : # A gérer nouvelles séries # nouvelles_series(_Current_Station_ID, _Current_Station_ID_Old, _Current_Serie_ID, 1, _Current_Ent) # type: ignore - # print (f"\033[34m\tA vérifier dans suivi_serie nouvelles séries inverses depuis {_Current_Station_ID} - {Next_Station_ID_2}, {Next_Station_ID_1}\033[0m") + # print (f"\033[34m\tA vérifier dans suivi_serie nouvelles séries inverses depuis {_Current_Station_ID} - {Next_Station_ID_2}, {Next_Station_ID_1}{Colors.ENDC}") # nouvelles_series(_Current_Station_ID, _Current_Station_ID_Old, _Current_Serie_ID, -1, _Current_Ent) return @@ -838,7 +842,7 @@ def suivi_serie( _Current_Serie_ID, bar) : _Current_Station_ID = int(_Serie[0][4]) _Next_Station_ID = sql_station_arrivee(_Current_Station_ID) # type: ignore _Current_Nre_Shot = 0 - #print(f"\tDébut suivi serie inverse {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot} Next station: {_Next_Station_ID}") # type: ignore + #print(f"Début suivi serie inverse {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot} Next station: {_Next_Station_ID}") # type: ignore _ID_Suite = 0 _Force = False @@ -846,7 +850,7 @@ def suivi_serie( _Current_Serie_ID, bar) : while int(_Next_Station_ID[_ID_Suite][0]) != int(_Serie[0][2]) : # type: ignore _ID_Suite += 1 if _ID_Suite >= len(_Next_Station_ID): # type: ignore - # print(f"\t \033[34mA vérifier, pas de suite trouvée à la serie inverse: {_Current_Serie_ID} station:{_Current_Station_ID}, shot: {_Current_Shot}\033[0m") + # print(f"\033[34mA vérifier, pas de suite trouvée à la serie inverse: {_Current_Serie_ID} station:{_Current_Station_ID}, shot: {_Current_Shot}{Colors.ENDC}") #error_count += 1 return @@ -893,7 +897,7 @@ def suivi_serie( _Current_Serie_ID, bar) : WHERE SHOT_ID = {_Current_Shot} """) - #print(f"\tSuivi serie inverse {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}, Next station: {_Next_Station_ID}") + #print(f"Suivi serie inverse {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}, Next station: {_Next_Station_ID}") conn.commit() depart = sql_station_depart(_Current_Station_ID) @@ -946,20 +950,20 @@ def suivi_serie( _Current_Serie_ID, bar) : depart = sql_station_depart(_Current_Station_ID) # type: ignore if (len(_Next_Station_ID)==0): # type: ignore # fin de la série - # print (f"\tFin de la série inverse: {_Current_Serie_ID} (pas de suite) station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") + # print (f"Fin de la série inverse: {_Current_Serie_ID} (pas de suite) station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, 1, _Current_Ent) # type: ignore if (len(depart)>=1):# type: ignore nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, -1, _Current_Ent) # type: ignore else : nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, -1, _Current_Ent) # type: ignore - # print (f"\tFin de la série inverse: {_Current_Serie_ID} station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") + # print (f"Fin de la série inverse: {_Current_Serie_ID} station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") if (len(depart)>=1):# type: ignore nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, 1, _Current_Ent) # type: ignore elif _Direction == 1 : _Current_Station_ID = int(_Serie[0][2]) _Next_Station_ID = sql_station_depart(_Current_Station_ID) _Current_Nre_Shot = 0 - #print(f"\tDébut suivi serie directe {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot} Next station: {_Next_Station_ID}") + #print(f"Début suivi serie directe {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot} Next station: {_Next_Station_ID}") _ID_Suite = 0 _Force = False @@ -967,7 +971,7 @@ def suivi_serie( _Current_Serie_ID, bar) : while int(_Next_Station_ID[_ID_Suite][0]) != int(_Serie[0][4]) : # type: ignore _ID_Suite += 1 if _ID_Suite >= len(_Next_Station_ID): # type: ignore - # print(f"\t \033[34mA vérifier, pas de suite trouvée à la serie directe: {_Current_Serie_ID}, Station: {_Current_Station_ID}, shot: {_Current_Shot}\033[0m") + # print(f"\033[34mA vérifier, pas de suite trouvée à la serie directe: {_Current_Serie_ID}, Station: {_Current_Station_ID}, shot: {_Current_Shot}{Colors.ENDC}") # error_count += 1 return @@ -1017,7 +1021,7 @@ def suivi_serie( _Current_Serie_ID, bar) : """) conn.commit() - #print(f"\tSuivi serie directe {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot} Next station: {_Next_Station_ID}") + #print(f"Suivi serie directe {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot} Next station: {_Next_Station_ID}") arrivee = sql_station_arrivee(_Current_Station_ID) @@ -1066,18 +1070,18 @@ def suivi_serie( _Current_Serie_ID, bar) : arrivee = sql_station_arrivee(_Current_Next_Station) # type: ignore if (len(_Next_Station_ID)==0): # type: ignore # fin de la série - # print (f"\tFin de la série directe: {_Current_Serie_ID} (pas de suite) à la station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") + # print (f"Fin de la série directe: {_Current_Serie_ID} (pas de suite) à la station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, -1, _Current_Ent) # type: ignore if (len(arrivee)>=1): # type: ignore nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, 1, _Current_Ent) # type: ignore else : nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, 1, _Current_Ent) # type: ignore - # print (f"\tFin de la série directe: {_Current_Serie_ID} station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") + # print (f"Fin de la série directe: {_Current_Serie_ID} station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") if (len(arrivee)>=1): # type: ignore nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, -1, _Current_Ent) # type: ignore except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête de lecture de la série\033[0m {_Current_Serie_ID}\033[91m, suivi_serie:\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête de lecture de la série{Colors.ENDC} {_Current_Serie_ID}{Colors.ERROR}, suivi_serie:{Colors.ENDC} {e}") error_count += 1 return @@ -1114,7 +1118,7 @@ def nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_I # _Next_Station = cursor.fetchall() if _Next_Station is None: # type: ignore - print(f"Pas de série crées à la station: {_Current_Station_ID}") + log.warning(f"Pas de série crées à la station: {Colors.ENDC}{_Current_Station_ID}") return # boucle sur liste _Next_Station for Depart in _Next_Station: # type: ignore @@ -1138,7 +1142,7 @@ def nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_I STATION_ENT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (_Current_Serie_ID, _Current_Station_ID, -1, Depart[0], -1, 0.0, 0.0, 0.0, 1,_STATION_ENT_ID)) conn.commit() - # print(f"\tCréation Série directe: {cursor.lastrowid} depuis la station: {_Current_Station_ID} vers {Depart[0]} ") + # print(f"Création Série directe: {cursor.lastrowid} depuis la station: {_Current_Station_ID} vers {Depart[0]} ") elif _DIRECTION == -1 : cursor.execute(f""" INSERT INTO SERIE ( @@ -1155,10 +1159,10 @@ def nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_I VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (-1, Depart[0], _Current_Serie_ID, _Current_Station_ID, -1, 0.0, 0.0, 0.0, -1,_STATION_ENT_ID)) conn.commit() - # print(f"\tCréation Série inv.: {cursor.lastrowid} depuis {Depart[0]} vers la station: {_Current_Station_ID}") + # print(f"Création Série inv.: {cursor.lastrowid} depuis {Depart[0]} vers la station: {_Current_Station_ID}") except sqlite3.Error as e: - print(f"\033[91mErreur lors de la requête (nouvelle_serie):\033[0m {e}") + log.error(f"Erreur lors de la requête (nouvelle_serie):{Colors.ENDC} {e}") error_count += 1 return @@ -1236,13 +1240,13 @@ def test_jonction(station, serie, entree) : retour = cursor.fetchall() cursor.execute(f"SELECT JONCTION.SERIE_ID FROM JONCTION WHERE JONCTION.STATION_ID = {row[0]}") _serie = cursor.fetchall() - # print (f"\tJonction à proximité de la Station_ID: {row[0]}, retour: {str(val)}, serie {serie} - {_serie[0][0]}, entrée {entree} - {retour[0][0]}") + # print (f"Jonction à proximité de la Station_ID: {row[0]}, retour: {str(val)}, serie {serie} - {_serie[0][0]}, entrée {entree} - {retour[0][0]}") if (retour[0][0] != entree) and (retour[0][0] != None) : - print (f"\033[36m\t Jonction à la Station_ID: {row[0]} entre les entrées {entree} et {retour[0][0]}\033[0m") + log.info(f"Jonction à la Station_ID: {Colors.ENDC}{row[0]}{Colors.INFO} entre les entrées {Colors.ENDC}{entree}{Colors.INFO} et {Colors.ENDC}{retour[0][0]}") cursor.execute(f"INSERT INTO RESEAU ( STATION_JONC, ENT_1, ENT_2) VALUES (?, ?, ?)", (row[0], entree, retour[0][0])) conn.commit() # if _serie[0][0] != serie and (_serie[0][0] != None): - # print (f"\033[34m\tJonction à la Station_ID: {row[0]} entre les series {serie} et {_serie[0][0]}\033[0m") + # print (f"\033[34m\tJonction à la Station_ID: {row[0]} entre les series {serie} et {_serie[0][0]}{Colors.ENDC}") cursor.execute(f"SELECT JONCTION.STATION_TYPE FROM JONCTION WHERE JONCTION.STATION_ID = {station}") @@ -1250,7 +1254,7 @@ def test_jonction(station, serie, entree) : val = str(retour[0]) if val == '(None,)' : - #print (f"\tPas de jonction à la Station_ID: {station}, retour: {val}") + #print (f"Pas de jonction à la Station_ID: {station}, retour: {val}") return False else : cursor.execute(f"UPDATE JONCTION SET STATION_TYPE = ? WHERE id = ?", ('jon', station)) @@ -1258,22 +1262,21 @@ def test_jonction(station, serie, entree) : retour = cursor.fetchall() cursor.execute(f"SELECT JONCTION.SERIE_ID FROM JONCTION WHERE JONCTION.STATION_ID = {station}") _serie = cursor.fetchall() - # print (f"\tJonction à proximité de la Station_ID: {row[0]}, retour: {str(val)}, serie {serie} - {_serie[0][0]}, entrée {entree} - {retour[0][0]}") + # print (f"Jonction à proximité de la Station_ID: {row[0]}, retour: {str(val)}, serie {serie} - {_serie[0][0]}, entrée {entree} - {retour[0][0]}") if retour[0][0] != entree : - print (f"\033[0m\t Jonction à la Station_ID: {station} entre les entrées {entree} et {retour[0][0]}\033[0m") + log.info(f"Jonction à la Station_ID: {Colors.ENDC}{station}{Colors.INFO} entre les entrées {Colors.ENDC}{entree}{Colors.INFO} et {Colors.ENDC}{retour[0][0]}") if _serie[0][0] != serie : - print (f"\033[0m\t Jonction à la Station_ID: {station} entre les series {serie} et {_serie[0][0]}\033[0m") + log.info (f"Jonction à la Station_ID: {Colors.ENDC}{station}{Colors.INFO} entre les series {Colors.ENDC}{serie}{Colors.INFO} et {Colors.ENDC}{_serie[0][0]}") return True except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requêtes (test_jonction): {e}\033[0m") + log.error(f"Erreur lors de l'exécution de la requêtes (test_jonction): {Colors.ENDC}{e}") error_count += 1 return ##################################################################################################################################### # Fonction pour exécuter une requête et sauvegarder les résultats dans un fichier texte # -# # ##################################################################################################################################### def calcul_stats(output_file): global error_count @@ -1281,24 +1284,24 @@ def calcul_stats(output_file): global _largeurColTete try: - print(f"\033[1;32mPhase 5: Écriture des statistiques dans fichier \033[0m{safe_relpath(output_file)}") + log.info(f"Phase 5: Écriture des statistiques dans fichier {Colors.ENDC}{safe_relpath(output_file, 2)}") # Enregistrement des résultats dans un fichier texte output_file_ligne_md = [] output_file_ligne_csv = [] for i in range(9): - output_file_ligne_csv.append(titre[i].ljust(120)+"*\n") + output_file_ligne_csv.append(titre[i].ljust(118)+"*\n") output_file_ligne_md.extend([ f"--------------\n", f"# {titre[1].strip()[2:]}\n", - f"- ** {titre[2].strip()[2:]}**\n", - f"- ** {titre[3].strip()[2:]}**\n", - f"- ** {titre[4].strip()[2:]}**\n", - f"- ** {titre[5].strip()[2:]}**\n", - f"- ** {titre[6].strip()[2:]}**\n", - f"- ** {titre[7].strip()[2:]}**\n", - f"--------------\n", + f"- {titre[2].strip()[2:]}\n", + f"- {titre[3].strip()[2:]}\n", + f"- {titre[4].strip()[2:]}\n", + f"- {titre[5].strip()[2:]}\n", + f"- {titre[6].strip()[2:]}\n", + f"- {titre[7].strip()[2:]}\n", + f"--------------\n\n", ]) @@ -1316,18 +1319,17 @@ def calcul_stats(output_file): vide ="-".ljust(_largeurCol) output_file_ligne_csv.append( - f"**Développement total centerline:**\t%s\t%s\t%s\t%s\t%s\tDev.(m), Dupl.(m), Surf.(m)\n" + f"**Développement total centerline (m):**\tdéveloppement: %s,\tdupliqué: %s,\tsurface: %s\n" %(str("{:.2f}".format(results[0][0]).ljust(_largeurCol)), str("{:.2f}".format(results[0][1]).ljust(_largeurCol)), str("{:.2f}".format(results[0][2]).ljust(_largeurCol)), - str(vide), - str(vide))) + )) output_file_ligne_md.append( - f"**Développement total des centerlines (m):** " - f", Développement: '{results[0][0]:.2f}'" - f", Dupliqué: '{results[0][1]:.2f}'" - f", Surface: '{results[0][2]:.2f}'\n" + f"**Développement total des centerlines (m):**" + f" développement: `{results[0][0]:.2f}`" + f", dupliqué: `{results[0][1]:.2f}`" + f", surface: `{results[0][2]:.2f}`\n" ) cursor.execute("SELECT COUNT(*) AS nbre FROM JONCTION WHERE STATION_TYPE IS NULL") @@ -1335,13 +1337,16 @@ def calcul_stats(output_file): compteur = int(_compteur[0][0]) if compteur > 0 : # type: ignore - output_file_ligne_md.append(f"!!Attention, {compteur} station(s) non comptabilisée(s) et raccordée(s)\n\n") + output_file_ligne_md.append(f"!!Attention, `{compteur}` station(s) non comptabilisée(s) et raccordée(s)\n\n") output_file_ligne_csv.append(f"Attention, {compteur} station(s) non comptabilisée(s) et raccordée(s)\n\n") + else : + output_file_ligne_md.append(f"Toutes les stations sont comptabilisées et raccordées\n\n") + output_file_ligne_csv.append(f"Toutes les stations sont comptabilisées et raccordées\n\n") results=sql_bilan_reseaux() - def format_markdown_row(row_data): - return '| ' + ' | '.join(f"{str(item):>10}" for item in row_data) + ' |' + # def format_markdown_row(row_data): + # return '| ' + ' | '.join(f"{str(item):>10}" for item in row_data) + ' |' if results[0][0] != None :# type: ignore output_file_ligne_csv.append("Développement total par réseaux\n") @@ -1351,7 +1356,7 @@ def calcul_stats(output_file): #print('Développement total: ' + formatted_row + 'm') - output_file_ligne_md.append(f"--------------\n") + output_file_ligne_md.append(f"\n--------------\n") output_file_ligne_md.append("**Développement total par réseaux**\n") headers = ["Entrée(s)", "Nbre", "Dev.(m)", "Prof.(m)", "Dupl.(m)", "Surf.(m)", "Visées", "ID Sta.", "Alt. min(m)", "ID Sta.", "Alt. max(m)"] @@ -1366,7 +1371,7 @@ def calcul_stats(output_file): results=sql_bilan_annee() if results[0][0] != None :# type: ignore - output_file_ligne_csv.append("\nDéveloppement total topographié par année(s)**\n") + output_file_ligne_csv.append("\nDéveloppement total topographié par année(s)\n") for row in results: # type: ignore if row[1].strip() != "0.00" or row[3].strip() != "0.00" or row[5].strip() != "0.00" : formatted_row = '\t'.join(map(str, row)) @@ -1385,6 +1390,8 @@ def calcul_stats(output_file): formatted_row = [str(v) for v in row] output_file_ligne_md.append("| " + " | ".join(formatted_row) + " |\n") + + output_file_ligne_md.append(f"\n--------------\n") Rose(output_file_name_rose) @@ -1405,14 +1412,14 @@ def calcul_stats(output_file): duree_formatee = "{:02}(s)".format(secondes) if error_count == 0: - output_file_ligne_csv[7] = "* Durée calcul: " + duree_formatee + " sans erreur" - output_file_ligne_md[7] = "- ** Durée calcul : " + duree_formatee + " sans erreur**\n" - output_file_ligne_csv[7] = output_file_ligne_csv[7].ljust(120)+"*\n" + output_file_ligne_csv[7] = "* Durée calcul : " + duree_formatee + " sans erreur" + output_file_ligne_md[7] = "- Durée calcul : " + duree_formatee + " sans erreur\n" + output_file_ligne_csv[7] = output_file_ligne_csv[7].ljust(118)+"*\n" else : - output_file_ligne_csv[7] = "* Durée calcul: " + duree_formatee + " avec erreur(s): " + str(error_count) - output_file_ligne_md[7] = "- ** Durée calcul : ** " + duree_formatee + "!! avec erreur(s): " + str(error_count) + "**\n" - output_file_ligne_csv[7] = output_file_ligne_csv[7].ljust(120)+"*\n" + output_file_ligne_csv[7] = "* Durée calcul : " + duree_formatee + " avec erreur(s): " + str(error_count) + output_file_ligne_md[7] = "- Durée calcul : " + duree_formatee + "!! avec erreur(s): " + str(error_count) + "\n" + output_file_ligne_csv[7] = output_file_ligne_csv[7].ljust(118)+"*\n" with open(output_file + ".md", 'w', encoding='utf-8') as file: file.writelines(output_file_ligne_md) @@ -1421,14 +1428,14 @@ def calcul_stats(output_file): file.writelines(output_file_ligne_csv) if error_count == 0 : - print(f"\033[1;32mPhase 6: Fin de traitement en \033[0m" + duree_formatee + f"\033[1;32m, résultats enregistrés dans \033[0m{safe_relpath(output_file)}") + log.info(f"Phase 6: Fin de traitement en {Colors.ENDC}" + duree_formatee + f"{Colors.INFO}, résultats enregistrés dans {Colors.ENDC}{safe_relpath(output_file, 2)}") else : - print(f"\033[1;32mPhase 6: Fin de traitement en \033[0m" + duree_formatee - + f",\033[91m avec \033[0m{error_count}\033[91m erreur(s), \033[1;32mrésultats enregistrés dans \033[0m{safe_relpath(output_file)}") + log.warning(f"Phase 6: Fin de traitement en {Colors.ENDC}" + duree_formatee + + f",{Colors.WARNING} avec {Colors.ENDC}{error_count}{Colors.WARNING} erreur(s), {Colors.INFO}résultats enregistrés dans {Colors.ENDC}{safe_relpath(output_file, 2)}") except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution des requêtes calcul_stats:\033[0m {e}") + log.error(f"Erreur lors de l'exécution des requêtes calcul_stats:{Colors.ENDC} {e}") error_count += 1 output_file_ligne_md.append(f"!!! Erreur lors de l'exécution des requêtes calcul_stats: {e}\n") output_file_ligne_csv.append(f"Erreur lors de l'exécution des requêtes calcul_stats: {e}\n") @@ -1442,13 +1449,13 @@ def calcul_stats(output_file): return except FileNotFoundError: - print(f"\033[91mErreur d'ouverture du fichier: \033[0m{safe_relpath(output_file)} ") + log.error(f"Erreur d'ouverture du fichier: {Colors.ENDC}{safe_relpath(output_file)} ") error_count += 1 return except Exception as e: - print(f"\033[91mErreur lors de l'exécution de calcul_stats:\033[0m {e}") + log.error(f"Erreur lors de l'exécution de calcul_stats:{Colors.ENDC} {e}") error_count += 1 output_file_ligne_md.append(f"!! Erreur lors de l'exécution de calcul_stats: {e}\n") output_file_ligne_csv.append(f"Erreur lors de l'exécution de calcul_stats: {e}\n") @@ -1464,7 +1471,7 @@ def calcul_stats(output_file): return ##################################################################################################################################### -# # Requête : Table des entrées (Liste des entrées avec coordonnées) # +# Requête : Table des entrées (Liste des entrées avec coordonnées) # ##################################################################################################################################### def sql_liste_entree(): global error_count @@ -1509,39 +1516,39 @@ def sql_liste_entree(): # result_fix = cursor.fetchall() if len(result_ent) == 0 : error_count += 1 - print(f"\t \033[91mAttention aucune entrée ou point fix comptabilisé\033[0m") + log.warning(f"Attention aucune entrée ou point fix comptabilisé") else : - print(f"\t \033[32mTable des STATION, entrée et fix nbre: \033[0m{len(result_ent)}") + log.info(f"Table des STATION, entrée et fix nbre: {Colors.ENDC}{len(result_ent)}") return result_ent # if len(result_ent) == 0: - # print(f"\033[91mPas d'entrées\033[0m") + # print(f"{Colors.RED}Pas d'entrées{Colors.ENDC}") # if len(result_fix) == 0: - # print(f"\033[91mPas de points fixes\033[0m") + # print(f"{Colors.RED}Pas de points fixes{Colors.ENDC}") # return None # else : - # print(f"\tTable des STATION, point fixe nbre: {len(result_fix)}") + # print(f"Table des STATION, point fixe nbre: {len(result_fix)}") # return result_fix # elif len(result_ent) == len(result_fix) : - # print(f"\tTable des STATION, entrée nbre: {len(result_ent)}") - # # print(f"\tTable des STATION, point fixe nbre: {len(result_fix)}") + # print(f"Table des STATION, entrée nbre: {len(result_ent)}") + # # print(f"Table des STATION, point fixe nbre: {len(result_fix)}") # return result_ent # elif len(result_ent) > len(result_fix) : - # print(f"\033[91mA gérer Points fixes > entrées, traitement uniquement des entrées\033[0m") + # print(f"{Colors.RED}A gérer Points fixes > entrées, traitement uniquement des entrées{Colors.ENDC}") # return result_ent # elif len(result_ent) < len(result_fix) : - # print(f"\033[91mA gérer Points fixes < entrées, traitement uniquement des points fixes\033[0m") + # print(f"{Colors.RED}A gérer Points fixes < entrées, traitement uniquement des points fixes{Colors.ENDC}") # return result_fix except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête 4 (sql_liste_entree):\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête 4 (sql_liste_entree):{Colors.ENDC} {e}") error_count += 1 return None return ##################################################################################################################################### -# # Requête : Table des séries vides # +# Requête : Table des séries vides # ##################################################################################################################################### def sql_serie_vides(): global error_count @@ -1558,14 +1565,14 @@ def sql_serie_vides(): return retour except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête (sql_serie_vides): {e}\033[0m") + log.error(f"Erreur lors de l'exécution de la requête (sql_serie_vides): {Colors.ENDC}{e}") error_count += 1 return None return ##################################################################################################################################### -# # Requête: From_To (recherche si il y a un départ dans le sens From vers To depuis la station Current_Station_ID) # +# Requête: From_To (recherche si il y a un départ dans le sens From vers To depuis la station Current_Station_ID) # ##################################################################################################################################### def sql_station_depart(station): global error_count @@ -1594,18 +1601,18 @@ def sql_station_depart(station): -- AND ( SELECT SHOT.TO_ID FROM SHOT WHERE SHOT.FROM_ID = TO_ID_RESULT) """) retour = cursor.fetchall() - # if len(retour) == 0 : print(f"\tAucun départ depuis la station: {station}") + # if len(retour) == 0 : print(f"Aucun départ depuis la station: {station}") return retour except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête 6 (sql_station_depart) code:\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête 6 (sql_station_depart) code:{Colors.ENDC} {e}") error_count += 1 return None return ##################################################################################################################################### -# # Requête : To_From (recherche si il y a un départ dans le sens To vers From depuis la station Current_Station_ID) # +# Requête : To_From (recherche si il y a un départ dans le sens To vers From depuis la station Current_Station_ID) # ##################################################################################################################################### def sql_station_arrivee(station): global error_count @@ -1634,18 +1641,18 @@ def sql_station_arrivee(station): --AND ( SELECT JONCTION.STATION_TYPE FROM JONCTION WHERE SHOT.TO_ID = FROM_ID_RESULT """) retour = cursor.fetchall() - # if len(retour) == 0 print(f"\tAucune arrivée depuis la station: {station}") + # if len(retour) == 0 print(f"Aucune arrivée depuis la station: {station}") return retour except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête 7 (sql_station_arrivee) code:\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête 7 (sql_station_arrivee) code:{Colors.ENDC} {e}") error_count += 1 return None return ##################################################################################################################################### -# #-- Bilan table série # +# Bilan table série # ##################################################################################################################################### def sql_bilan_serie(): global error_count @@ -1668,14 +1675,14 @@ def sql_bilan_serie(): return retour except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête 11 (sql_bilan_serie):\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête 11 (sql_bilan_serie):{Colors.ENDC} {e}") error_count += 1 return None return ##################################################################################################################################### -# #-- Bilan table série By Réseaux # +# Bilan table série By Réseaux # ##################################################################################################################################### def sql_bilan_reseaux(): global error_count @@ -2333,13 +2340,12 @@ def sql_bilan_reseaux(): return _retour # type: ignore except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête (sql_bilan_reseaux):\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête (sql_bilan_reseaux):{Colors.ENDC} {e}") error_count += 1 return retour return - ##################################################################################################################################### # Optimisation, création des indexes # ##################################################################################################################################### @@ -2396,7 +2402,7 @@ def sql_optimisation(): return except Exception as e: - print(f"\033[91mErreur lors de l'exécution de la requête (sql_optimisation):\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête (sql_optimisation):{Colors.ENDC} {e}") error_count += 1 return @@ -2404,13 +2410,13 @@ def sql_optimisation(): return ##################################################################################################################################### -# # Clé de tri # +# Clé de tri # ##################################################################################################################################### def cle_tri(element): return float(element[2]) ##################################################################################################################################### -# #-- Bilan topo par années # +# Bilan topo par années # ##################################################################################################################################### def sql_bilan_annee(): global error_count @@ -2502,18 +2508,18 @@ def sql_bilan_annee(): except sqlite3.Error as e: - print(f"\033[91mErreur lors de l'exécution de la requête (sql_bilan_annee):\033[0m {e}") + log.error(f"Erreur lors de l'exécution de la requête (sql_bilan_annee):{Colors.ENDC} {e}") error_count += 1 return None except Exception as e: - print(f"\033[91mErreur lors de l'exécution de sql_bilan_annee:\033[0m {e}") + log.error(f"Erreur lors de l'exécution de sql_bilan_annee:{Colors.ENDC} {e}") error_count += 1 return None ##################################################################################################################################### -# diagramme de "rose" # +# diagramme de "rose" # ##################################################################################################################################### def Rose(graph_name, bins = 72): """ @@ -2648,7 +2654,7 @@ def PlotExploYears(graph_name, rangeyear = [1959, datetime.now().year], systems if len(systems) > 1: # Check if the number of colors is enough for the number of systems if len(systems)>len(colores): - raise NameError('\033[91mERROR:\033[00m Number of colors lower than the number of systems!\n\tedit the code to add colors in the list, or lower the number of systems to plot') + raise NameError(f'{Colors.RED}ERROR:Number of colors lower than the number of systems!\n\tedit the code to add colors in the list, or lower the number of systems to plot') # Copy the length column in an other column to trace of it sommeplot[systems[0]] = sommeplot["Longueur"] @@ -2736,94 +2742,7 @@ def PlotExploYears(graph_name, rangeyear = [1959, datetime.now().year], systems return -################################################################################################# -# fonction pour réduire l'affichage des chemins long # -################################################################################################# -def safe_relpath(path, base_dir=None, max_depth=3, max_name_len=50, prefix="~"): - """ - Retourne un chemin lisible et sûr pour affichage (logs / UI). - - Compatible Windows / Linux / macOS - - Tronque la profondeur du chemin - - Tronque le nom de fichier si trop long - - Ne lève jamais d'exception - """ - - try: - path = Path(path).expanduser().resolve() - except Exception: - return str(path) - - try: - base = Path(base_dir).expanduser().resolve() if base_dir else Path.cwd().resolve() - except Exception: - base = None - - name = path.name or str(path) - if len(name) > max_name_len: - stem = path.stem[: max(1, max_name_len - 6)] - name = f"{stem}...{path.suffix}" - - try: - if base: - rel = path.relative_to(base) - parts = list(rel.parts) - else: - raise ValueError - except Exception: - parts = list(path.parts) - - if not parts: - parts = ["."] - - if isinstance(max_depth, int) and max_depth > 0 and len(parts) > max_depth: - parts = parts[-max_depth:] - parts.insert(0, prefix) - - if parts and parts[-1] not in (".", os.sep): - parts[-1] = name - - try: - return os.path.join(*parts) - except Exception: - return name - -################################################################################################# -# Coloration des messages d'aide d'arg # -################################################################################################# -def colored_help(parser): - """ - Affiche l'aide colorée pour les arguments de la ligne de commande. - - Args: - parser (argparse.ArgumentParser): Le parseur d'arguments. - Returns: - None - - """ - # Captures the help output - help_text = parser.format_help() - - # Coloration des différentes parties - colored_help_text = help_text.replace( - 'usage:', f'\033[91musage:\033[0m' - ).replace( - 'options:', f'\033[92moptions:\033[0m' - ).replace('positional arguments:', f'\033[94mpositional arguments:\033[0m' - ).replace(', --help', f'\033[94m, --help:\033[0m' - ).replace('elp:', f'\033[94melp\033[0m') - - # Surligner les arguments - for action in parser._actions: - if action.option_strings: - # Colorer les options (--xyz) - for opt in action.option_strings: - colored_help_text = colored_help_text.replace(opt, f'\033[94m{opt}\033[0m').replace('--help', f'\033[94m--help:\033[0m') - - # Imprimer le texte coloré - print(colored_help_text) - sys.exit(1) - ##################################################################################################################################### # # # Main # @@ -2838,6 +2757,7 @@ if __name__ == '__main__': input_file_name = "" outputs_path = "./Test/" inputs_path = "./Test/" + # if not os.path.exists(outputs_path): os.makedirs(outputs_path) if os.name == 'posix': os.system('clear') # Linux, MacOS @@ -2846,8 +2766,11 @@ if __name__ == '__main__': maintenant = datetime.now() + ################################################################################################# + # Parse arguments # + ################################################################################################# parser = argparse.ArgumentParser( - description=f"Calcul des statistiques par entrées d'une BD Therion", + description=f"{Colors.HEADER}Calcul des statistiques par entrées d'une BD Therion", formatter_class=argparse.RawTextHelpFormatter) parser.print_help = colored_help.__get__(parser) parser.add_argument( @@ -2860,11 +2783,12 @@ if __name__ == '__main__': ) ) - parser.add_argument("--file", help="Chemin vers le fichier SQL d'entrée (pas de d'option : fenêtre de choix)") - parser.epilog = (f"Commande therion (fichier .thconfig) : export database -o Outputs/database.sql") + parser.add_argument("--file", help="Chemin vers le fichier SQL d'entrée (par défaut : fenêtre de choix)") + parser.epilog = (f"{Colors.HEADER}Pour générer fichier sql, commande therion dans .thconfig -> {Colors.ENDC}export database -o Outputs/database.sql") # Analyser les arguments de ligne de commande args = parser.parse_args() + if not args.file: # Si aucun fichier n'est fourni en ligne de commande, ouvrir une fenêtre Tkinter pour sélectionner un fichier # input_file = "rabbit.sql" # Erreur car pas de point fix ou d'entrée python @@ -2875,7 +2799,7 @@ if __name__ == '__main__': input_file_name = filedialog.askopenfilename( title="Sélectionnez le fichier SQL", filetypes=(("Fichiers SQL", "*.sql"), ("Tous les fichiers", "*.*")) ) if not input_file_name: - print("Aucun fichier sélectionné. Le programme va se terminer.") + print(f"{Colors.ERROR}Aucun fichier sélectionné. Le programme va se terminer.") sys.exit() outputs_path = os.path.dirname(input_file_name) + "/" @@ -2886,41 +2810,50 @@ if __name__ == '__main__': input_file_name = args.file # print("Le paramètre fourni est:", input_file_name) if os.path.isfile(input_file_name) is False : - print(f"\033[91mErreur : fichier \033[0m{input_file_name}\033[91m inexistant\033[0m") - print(f"\033[92mCommande : \033[0mpython pythStat.py votre_fichier_therion.sql") + print(f"{Colors.ERROR}Erreur : fichier {Colors.ENDC}{input_file_name}{Colors.ERROR} inexistant{Colors.ENDC}") + print(f"{Colors.ERROR}Commande : {Colors.ENDC}python pythStat.py -file votre_fichier_therion.sql") sys.exit() + else : outputs_path = os.path.dirname(input_file_name) + "/" input_file = os.path.basename(input_file_name) if os.name == 'posix': os.system('clear') # Linux, MacOS + elif os.name == 'nt': os.system('cls')# Windows + else: print("\n" * 100) - - outputfolder = outputs_path + "stat_" + input_file[:-4] + "_" + maintenant.strftime("%Y-%m-%d") + "/" + outputfolder = outputs_path + "Stats_" + input_file[:-4] + "_" + maintenant.strftime("%Y-%m-%d") + "/" if not os.path.exists(outputfolder): os.makedirs(outputfolder) - - output_file_name = outputfolder + input_file[:-4]+"_stats" - output_file_name_rose = outputfolder + input_file[:-4]+"_rose.pdf" - output_file_name_histo = outputfolder + input_file[:-4]+"_histo.pdf" - output_file_name_year = outputfolder + input_file[:-4]+"_year" - imported_database = outputfolder + input_file[:-4]+"_stats.db" - - _titre =['\033[1;32m************************************************************************************************************************\033[0m', - '\033[1;32m* Calcul des statistiques par entrées d\'une BD Therion\033[0m', - '\033[1;32m* Script pythStat par alexandre.pont@yahoo.fr\033[0m', - '\033[1;32m* Version : \033[0m' + Version, - '\033[1;32m* Fichier source : \033[0m' + safe_relpath(input_file_name), - '\033[1;32m* Dossier destination : \033[0m' + safe_relpath(outputfolder), - '\033[1;32m* Date : \033[0m' + maintenant.strftime("%Y-%m-%d %H:%M:%S"), - '\033[1;32m* \033[0m', - '\033[1;32m************************************************************************************************************************\033[0m'] - - - for i in range(9): print(_titre[i].ljust(131)+"\033[1;32m*\033[0m") - titre = [ligne.replace("\033[1;32m", "").replace("\033[0m", "") for ligne in _titre] + output_file_name_log = outputfolder + input_file[:-4] + "_log.log" + output_file_name = outputfolder + input_file[:-4] + "_stats" + output_file_name_rose = outputfolder + input_file[:-4] + "_rose.pdf" + output_file_name_histo = outputfolder + input_file[:-4] + "_histo.pdf" + output_file_name_year = outputfolder + input_file[:-4] + "_year" + imported_database = outputfolder + input_file[:-4] + "_stats.db" + + log = setup_logger(output_file_name_log, globalDat.debug_log) + + ################################################################################################# + # titre # + ################################################################################################# + + _titre =[f'{Colors.MAGENTA}{Colors.BOLD}**********************************************************************************************************************{Colors.ENDC}', + f'{Colors.MAGENTA}{Colors.BOLD}* Calcul des statistiques par entrées d\'une BD Therion{Colors.ENDC} ', + f'{Colors.MAGENTA}{Colors.BOLD}* Script pythStat par : {Colors.ENDC}alexandre.pont@yahoo.fr ', + f'{Colors.MAGENTA}{Colors.BOLD}* Version : {Colors.ENDC}{globalDat.Version} ', + f'{Colors.MAGENTA}{Colors.BOLD}* Fichier source : {Colors.ENDC}{safe_relpath(input_file_name)} ', + f'{Colors.MAGENTA}{Colors.BOLD}* Dossier destination : {Colors.ENDC}{safe_relpath(outputfolder)} ', + f'{Colors.MAGENTA}{Colors.BOLD}* Date : {Colors.ENDC}{maintenant.strftime("%Y-%m-%d %H:%M:%S")} ', + f'{Colors.MAGENTA}{Colors.BOLD}* {Colors.ENDC} ', + f'{Colors.MAGENTA}{Colors.BOLD}**********************************************************************************************************************{Colors.ENDC}'] + + + for i in range(9): log.info(_titre[i].ljust(131)+f"{Colors.MAGENTA}{Colors.BOLD}*{Colors.ENDC}") + + titre = [ligne.replace(f"{Colors.MAGENTA}{Colors.BOLD}", "").replace(f"{Colors.ENDC}", "") for ligne in _titre] if args.option == "sync" : importation_sql_data(input_file_name) diff --git a/Synthese-PSM_LARRA.thconfig b/Synthese-PSM_LARRA.thconfig index 62b5842..ea83395 100644 --- a/Synthese-PSM_LARRA.thconfig +++ b/Synthese-PSM_LARRA.thconfig @@ -279,7 +279,7 @@ export model -enable all -o Outputs/Synthese-PSM_LARRA.kml # export des statistiques de l'ensemble de la cavité # Attention, les points de départ et d'arrivée de chaque centreline correspondent # au second point et à l'avant dernier point de la série. -export database -fmt sql -o Outputs/database_Synthese-PSM_LARRA.sql +export database -fmt sql -o Outputs/DB_Synthese-PSM_LARRA.sql # Export des fichiers ESRI export map -proj plan -fmt esri -o Outputs/SHP/ -enc UTF-8