Code station and sensor names in the diagnostic case base (D-049)
Add the anonymiser-cas skill: a growing registry gives stable codes (S01, R1, C1), a stdlib script rewrites a case and renames its files, and graphique.py / vignettes.py take --alias to plot with codes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3478d77f1d
commit
a684349501
15 files changed
+203
-30
No files matched your search
@@ -0,0 +1,112 @@
|
||||
"""Anonymise un cas de la base de l'agent de diagnostic : la station et ses capteurs deviennent des codes stables.
|
||||
|
||||
Usage :
|
||||
python3 .claude/skills/anonymiser-cas/anonymiser.py data/<STATION>/ agents/diagnostic/cas/<dossier du cas>/
|
||||
réécrit les .md du cas et cas/INDEX.md, renomme fichiers et dossier ; échoue s'il reste un nom réel
|
||||
python3 .claude/skills/anonymiser-cas/anonymiser.py data/<STATION>/ --alias
|
||||
imprime NOM=CODE,... pour l'option --alias de graphique.py et vignettes.py
|
||||
python3 .claude/skills/anonymiser-cas/anonymiser.py --test
|
||||
Codes : S01, S02... pour les stations ; R1, R2... pour les références et C1, C2... pour les cibles, par station.
|
||||
Le registre (registre.csv, à côté) ne fait que grandir : un nom garde son code d'un cas à l'autre.
|
||||
"""
|
||||
import csv
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
ICI = os.path.dirname(os.path.abspath(__file__))
|
||||
RACINE = os.path.normpath(os.path.join(ICI, "..", "..", ".."))
|
||||
REGISTRE = os.path.join(ICI, "registre.csv")
|
||||
INDEX = os.path.join(RACINE, "agents", "diagnostic", "cas", "INDEX.md")
|
||||
sys.path.insert(0, os.path.join(RACINE, "agents", "diagnostic", "outils"))
|
||||
from donnees import charger, est_reference # noqa: E402
|
||||
|
||||
|
||||
def codes(dossier):
|
||||
"""{nom: code} de la station et de ses capteurs ; un nom inconnu reçoit le code suivant, ajouté au registre."""
|
||||
station = os.path.basename(os.path.normpath(dossier))
|
||||
par = charger(dossier)
|
||||
if not par:
|
||||
sys.exit(f"Aucun export « advanced » dans {dossier}.")
|
||||
lignes = list(csv.DictReader(open(REGISTRE, newline=""))) if os.path.exists(REGISTRE) else []
|
||||
connus = {(l["station"], l["nom"]): l["code"] for l in lignes}
|
||||
nouveaux = []
|
||||
if (station, station) not in connus:
|
||||
n = max((int(c[1:]) for (s, nom), c in connus.items() if s == nom), default=0)
|
||||
nouveaux.append((station, station, f"S{n + 1:02d}"))
|
||||
for prefixe, reference in (("R", True), ("C", False)):
|
||||
n = max((int(c[1:]) for (s, nom), c in connus.items() if s == station != nom and c[0] == prefixe), default=0)
|
||||
for nom in sorted(x for x in par if est_reference(par[x]) == reference and (station, x) not in connus):
|
||||
n += 1
|
||||
nouveaux.append((station, nom, f"{prefixe}{n}"))
|
||||
if nouveaux:
|
||||
with open(REGISTRE, "a", newline="") as f:
|
||||
w = csv.writer(f)
|
||||
if not lignes:
|
||||
w.writerow(("station", "nom", "code"))
|
||||
w.writerows(nouveaux)
|
||||
connus.update({(s, nom): c for s, nom, c in nouveaux})
|
||||
return station, {nom: c for (s, nom), c in connus.items() if s == station}
|
||||
|
||||
|
||||
def motif(table, station, casse=False):
|
||||
"""Les noms, du plus long au plus court, bornés par un caractère non alphanumérique (« _ » compris : un nom
|
||||
collé dans un nom de fichier est trouvé, mais BJ_C ne l'est pas dans PBJ_C). La station accepte espace ou « _ »
|
||||
et toute casse (PS_DES_COUDRES, « PS des Coudres »)."""
|
||||
parties = []
|
||||
for nom in sorted(table, key=len, reverse=True):
|
||||
p = re.escape(nom)
|
||||
parties.append(f"(?i:{p.replace('_', '[ _]')})" if nom == station else p)
|
||||
return re.compile(("(?i)" if casse else "") + r"(?<![A-Za-z0-9])(" + "|".join(parties) + r")(?![A-Za-z0-9])")
|
||||
|
||||
|
||||
def remplacer(texte, table, station):
|
||||
return motif(table, station).sub(lambda m: table.get(m.group(1), table[station]), texte)
|
||||
|
||||
|
||||
def anonymiser(dossier, cas):
|
||||
station, table = codes(dossier)
|
||||
textes = [os.path.join(r, f) for r, _, fs in os.walk(cas) for f in fs if f.endswith(".md")] + [INDEX]
|
||||
for p in textes:
|
||||
avant = open(p).read()
|
||||
apres = remplacer(avant, table, station)
|
||||
if apres != avant:
|
||||
open(p, "w").write(apres)
|
||||
for r, dossiers, fichiers in os.walk(cas, topdown=False):
|
||||
for f in fichiers + dossiers:
|
||||
if remplacer(f, table, station) != f:
|
||||
os.rename(os.path.join(r, f), os.path.join(r, remplacer(f, table, station)))
|
||||
parent, nom = os.path.split(os.path.normpath(cas))
|
||||
cas = os.path.join(parent, remplacer(nom, table, station))
|
||||
os.rename(os.path.join(parent, nom), cas)
|
||||
|
||||
reste = motif(table, station, casse=True)
|
||||
textes = [os.path.join(r, f) for r, _, fs in os.walk(cas) for f in fs if f.endswith(".md")] + [INDEX]
|
||||
residus = [f"{p} : {m.group(1)}" for p in textes for m in reste.finditer(open(p).read())]
|
||||
residus += [os.path.join(r, f) for r, ds, fs in os.walk(cas) for f in fs + ds if reste.search(f)]
|
||||
if residus:
|
||||
sys.exit("Noms réels restants (casse différente ?) :\n " + "\n ".join(residus))
|
||||
print(cas)
|
||||
print(", ".join(f"{n} → {c}" for n, c in sorted(table.items(), key=lambda x: x[1])))
|
||||
|
||||
|
||||
def _test():
|
||||
t = {"PS_DES_COUDRES": "S01", "BJ_C": "C1", "PBJ_C": "C7", "REF_G": "R3"}
|
||||
f = lambda s: remplacer(s, t, "PS_DES_COUDRES") # noqa: E731
|
||||
assert f("PBJ_C et BJ_C") == "C7 et C1"
|
||||
assert f("PS_DES_COUDRES_error_value_REF_G-BJ_C.png") == "S01_error_value_R3-C1.png"
|
||||
assert f("PS des Coudres, REF_GX, data/PS_DES_COUDRES/") == "S01, REF_GX, data/S01/"
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
a = sys.argv[1:]
|
||||
if a == ["--test"]:
|
||||
_test()
|
||||
elif len(a) == 2 and a[1] == "--alias":
|
||||
_, table = codes(a[0])
|
||||
print(",".join(f"{n}={c}" for n, c in sorted(table.items())))
|
||||
elif len(a) == 2:
|
||||
anonymiser(*a)
|
||||
else:
|
||||
sys.exit(__doc__)
|
||||
Reference in new issue
Block a user