Commit 1e677a8f authored by Delvallez Delvallez's avatar Delvallez Delvallez

conversion des perturbations et résultats d'un format au nouveau + implem...

conversion des perturbations et résultats d'un format au nouveau + implem nouveau format dans GenericAutomatizedPerturbation.py
parent 6260bd27
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Convertit un fichier texte décrivant des perturbations vers le format JSON.
Le fichier texte peut contenir :
mot1 -> mot2 : replace
mot1 -> : suppression (replace vers chaîne vide)
mot+ : prepend
+mot : append
Si le fichier ne contient que des perturbations replace, l'utilisateur
peut choisir de les interpréter comme :
- une liste de perturbations indépendantes
- une unique perturbation full_replace
"""
import argparse
import json
from pathlib import Path
# ----------------------------------------------------------------------
# Lecture du fichier texte
# ----------------------------------------------------------------------
def lire_perturbations(path):
"""Lit le fichier texte et renvoie la liste des perturbations."""
perturbations = []
with open(path, "r", encoding="utf-8") as f:
for ligne in f:
ligne = ligne.strip()
if not ligne:
continue
if "->" in ligne:
gauche, droite = ligne.split("->", 1)
perturbations.append({
"type": "replace",
"from": gauche.strip(),
"to": droite.strip(),
"name": ligne
})
elif ligne.endswith("+"):
mot = ligne[:-1].strip()
perturbations.append({
"type": "prepend",
"word": mot,
"name": ligne
})
elif ligne.startswith("+"):
mot = ligne[1:].strip()
perturbations.append({
"type": "append",
"word": mot,
"name": ligne
})
else:
raise ValueError(f"Perturbation inconnue : {ligne}")
return perturbations
# ----------------------------------------------------------------------
# Détection du cas full_replace
# ----------------------------------------------------------------------
def uniquement_replace(perturbations):
return all(p["type"] == "replace" for p in perturbations)
def demander_mode():
print()
print("Le fichier ne contient que des perturbations replace.")
print()
print("Comment souhaitez-vous l'interpréter ?")
print(" 1 - Liste de perturbations indépendantes")
print(" 2 - Une perturbation full_replace")
print()
while True:
choix = input("Votre choix (1/2) : ").strip()
if choix in ("1", "2"):
return choix
print("Veuillez répondre 1 ou 2.")
# ----------------------------------------------------------------------
# Construction du JSON
# ----------------------------------------------------------------------
def construire_json(perturbations, full_replace, descr):
if not uniquement_replace(perturbations):
return perturbations
if not full_replace:
return perturbations
return [{
"type": "full_replace",
"name": descr,
"compo": perturbations
}]
# ----------------------------------------------------------------------
# Sauvegarde
# ----------------------------------------------------------------------
def sauvegarder(obj, path):
with open(path, "w", encoding="utf-8") as f:
json.dump(
obj,
f,
ensure_ascii=False,
indent=4
)
# ----------------------------------------------------------------------
# Programme principal
# ----------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser(
description="Convertit un fichier txt de perturbations en JSON."
)
parser.add_argument(
"input",
help="Fichier texte d'entrée"
)
parser.add_argument(
"output",
nargs="?",
help="Fichier JSON de sortie (défaut : même nom)"
)
parser.add_argument(
"--full_replace",
action="store_true",
help="Traite le fichier fourni comme une perturbation full_replace. Le fichier ne doit donner que des perturbations replace."
)
parser.add_argument(
"--name",
help="Description de la perturbation full_replace"
)
args = parser.parse_args()
input_path = Path(args.input)
output_path = (
Path(args.output)
if args.output
else input_path.with_suffix(".json")
)
perturbations = lire_perturbations(input_path)
json_obj = construire_json(perturbations, args.full_replace, args.name)
sauvegarder(json_obj, output_path)
print(f"\nJSON enregistré dans : {output_path}")
if __name__ == "__main__":
main()
\ No newline at end of file
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Convertit un ancien fichier de résultats MechIR vers le nouveau format.
Cas gérés :
- replace
- prepend
- append
- full_replace
Dans le cas d'une perturbation full_replace, un fichier décrivant les
perturbations (nouveau format JSON) doit être fourni.
"""
import argparse
import json
from pathlib import Path
# ----------------------------------------------------------------------
# Lecture
# ----------------------------------------------------------------------
def charger_json(path):
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
# ----------------------------------------------------------------------
# Parsing d'une perturbation simple (pas full_replace)
# ----------------------------------------------------------------------
def perturbation_depuis_nom(name):
name = name.strip()
if "->" in name:
gauche, droite = name.split("->", 1)
return {
"type": "replace",
"from": gauche.strip(),
"to": droite.strip(),
"name": name
}
if name.endswith("+"):
return {
"type": "prepend",
"word": name[:-1].strip(),
"name": name
}
if name.startswith("+"):
return {
"type": "append",
"word": name[1:].strip(),
"name": name
}
raise ValueError(f"Impossible d'interpréter : {name}")
# ----------------------------------------------------------------------
# Chargement de la description d'une perturbation full_replace
# ----------------------------------------------------------------------
def charger_full_replace(path, n_occ_full_replace):
perts = charger_json(path)
if not isinstance(perts, list):
raise ValueError("Le fichier de description de perturbation est mal formé.")
full = [p for p in perts if p["type"] == "full_replace"]
if len(full) == 0:
raise ValueError("Aucune perturbation full_replace trouvée.")
if len(full) > 1 :
if n_occ_full_replace is None:
raise ValueError(
"Plusieurs perturbations full_replace présentes. "
"Le script ne sait pas laquelle utiliser."
)
if n_occ_full_replace >= len(full):
raise ValueError("Aucune perturbation full_replace ne correspond au numéro d'occurence donné")
return full[n_occ_full_replace]
return full[0]
# ----------------------------------------------------------------------
# Conversion
# ----------------------------------------------------------------------
def convertir(ancien, full_replace=None):
nouveau = []
for nom, valeurs in ancien.items():
if nom == "full_replace":
if full_replace is None:
raise ValueError(
"Le fichier contient une perturbation full_replace.\n"
"Veuillez fournir le fichier de description correspondant."
)
perturbation = full_replace
else:
perturbation = perturbation_depuis_nom(nom)
nouveau.append({
"perturbation": perturbation,
"results": {
"baseline_perf":
valeurs.get("baseline_perf"),
"perturbed_perf":
valeurs.get("perturbed_perf"),
"patching_mean":
valeurs.get("patching_mean"),
"patching_std":
valeurs.get("patching_std")
}
})
return nouveau
# ----------------------------------------------------------------------
# Sauvegarde
# ----------------------------------------------------------------------
def sauvegarder(obj, path):
with open(path, "w", encoding="utf-8") as f:
json.dump(
obj,
f,
ensure_ascii=False,
indent=4
)
# ----------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"input",
help="Ancien fichier JSON"
)
parser.add_argument(
"-p",
"--perturbations",
help="Fichier JSON des perturbations (nécessaire pour full_replace)"
)
parser.add_argument(
"-n",
"--perturbation_number",
help="Si plusieurs perturbations full_replace sont présentes dans le fichier JSON décrivant les pertubations, numéro d'occurence de la perturbation full_replace à considérer."
)
parser.add_argument(
"-o",
"--output",
help="Fichier de sortie"
)
args = parser.parse_args()
ancien = charger_json(args.input)
full_replace = None
if "full_replace" in ancien:
if args.perturbations is None:
parser.error(
"Le fichier contient une perturbation full_replace.\n"
"Veuillez fournir --perturbations."
)
full_replace = charger_full_replace(args.perturbations,n_occ_full_replace = args.perturbation_number)
output = (
Path(args.output)
if args.output
else Path(args.input).with_name(
Path(args.input).stem + "_v2.json"
)
)
nouveau = convertir(
ancien,
full_replace=full_replace
)
sauvegarder(nouveau, output)
print(f"Fichier créé : {output}")
if __name__ == "__main__":
main()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment