mirror of
https://github.com/Ladebeze66/llm_ticket3.git
synced 2025-12-13 17:37:05 +01:00
136 lines
5.2 KiB
Python
Executable File
136 lines
5.2 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
Script pour générer un fichier CSV à partir d'un rapport JSON
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import json
|
|
import csv
|
|
import logging
|
|
|
|
# Configuration du logging
|
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
logger = logging.getLogger("GenerateCSV")
|
|
|
|
def generate_csv_from_json(json_path, model_name=None):
|
|
"""
|
|
Génère un fichier CSV à partir du rapport JSON
|
|
|
|
Args:
|
|
json_path: Chemin vers le fichier JSON
|
|
model_name: Nom du modèle pour le nom du fichier CSV (facultatif)
|
|
"""
|
|
if not os.path.exists(json_path):
|
|
logger.error(f"Le fichier {json_path} n'existe pas")
|
|
return False
|
|
|
|
try:
|
|
# Charger le rapport JSON
|
|
with open(json_path, 'r', encoding='utf-8') as f:
|
|
rapport_data = json.load(f)
|
|
|
|
# Extraire l'ID du ticket
|
|
ticket_id = rapport_data.get("ticket_id", os.path.basename(json_path).split("_")[0])
|
|
|
|
# Extraire les échanges
|
|
chronologie_echanges = rapport_data.get("chronologie_echanges", [])
|
|
if not chronologie_echanges:
|
|
logger.error("Aucun échange trouvé dans le fichier JSON")
|
|
return False
|
|
|
|
# Déterminer le nom du modèle
|
|
if not model_name:
|
|
# Essayer de l'extraire des métadonnées
|
|
metadata = rapport_data.get("metadata", {})
|
|
model_name = metadata.get("model", "default").split(":")[0].lower()
|
|
|
|
# Créer le nom du fichier CSV
|
|
csv_path = os.path.join(os.path.dirname(json_path), f"{ticket_id}_{model_name}.csv")
|
|
|
|
# Générer le CSV complet avec toutes les colonnes
|
|
with open(csv_path, 'w', encoding='utf-8', newline='') as csvfile:
|
|
# Définir les en-têtes
|
|
fieldnames = ['Date', 'Émetteur', 'Type', 'Contenu']
|
|
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
|
|
|
|
# Écrire l'en-tête
|
|
writer.writeheader()
|
|
|
|
# Écrire les échanges
|
|
for echange in chronologie_echanges:
|
|
writer.writerow({
|
|
'Date': echange.get('date', ''),
|
|
'Émetteur': echange.get('emetteur', ''),
|
|
'Type': echange.get('type', ''),
|
|
'Contenu': echange.get('contenu', '')
|
|
})
|
|
|
|
logger.info(f"Fichier CSV complet généré: {csv_path}")
|
|
|
|
# Générer également une version simplifiée Q&R pour la compatibilité
|
|
qr_csv_path = os.path.join(os.path.dirname(json_path), f"{ticket_id}_{model_name}_qr.csv")
|
|
|
|
with open(qr_csv_path, 'w', encoding='utf-8', newline='') as csvfile:
|
|
# Définir les en-têtes simplifiés
|
|
qr_writer = csv.writer(csvfile)
|
|
qr_writer.writerow(['Question', 'Réponse'])
|
|
|
|
# Variables pour suivre les questions et réponses
|
|
current_question = None
|
|
|
|
# Parcourir les échanges et extraire les paires Q&R
|
|
for echange in chronologie_echanges:
|
|
emetteur = echange.get('emetteur', '').upper()
|
|
type_msg = echange.get('type', '').lower()
|
|
contenu = echange.get('contenu', '')
|
|
|
|
# Si c'est une question du client
|
|
if emetteur == 'CLIENT' and (type_msg == 'question' or '?' in contenu):
|
|
# Si une question précédente existe sans réponse, l'écrire avec une réponse vide
|
|
if current_question:
|
|
qr_writer.writerow([current_question, ''])
|
|
|
|
# Enregistrer la nouvelle question
|
|
current_question = contenu
|
|
|
|
# Si c'est une réponse ou un complément et qu'il y a une question en attente
|
|
elif emetteur == 'SUPPORT' and current_question:
|
|
# Préfixer la réponse pour la clarté
|
|
formatted_response = f"[{type_msg.upper()}] {contenu}"
|
|
|
|
# Écrire la paire question/réponse
|
|
qr_writer.writerow([current_question, formatted_response])
|
|
current_question = None
|
|
|
|
# Si une question reste sans réponse à la fin
|
|
if current_question:
|
|
qr_writer.writerow([current_question, ''])
|
|
|
|
logger.info(f"Fichier CSV Q&R simplifié généré: {qr_csv_path}")
|
|
|
|
return csv_path
|
|
|
|
except Exception as e:
|
|
logger.error(f"Erreur lors de la génération du CSV: {e}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
return False
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 2:
|
|
print("Usage: python generate_csv.py <path_to_json> [model_name]")
|
|
sys.exit(1)
|
|
|
|
json_path = sys.argv[1]
|
|
model_name = sys.argv[2] if len(sys.argv) > 2 else None
|
|
|
|
csv_path = generate_csv_from_json(json_path, model_name)
|
|
|
|
if csv_path:
|
|
print(f"\nFichier CSV généré avec succès: {csv_path} ✅")
|
|
print(f"Une version simplifiée Q&R a également été générée")
|
|
else:
|
|
print("\nÉchec de la génération du CSV ❌") |