mirror of
https://github.com/Ladebeze66/llm_ticket3.git
synced 2025-12-13 17:37:05 +01:00
169 lines
5.8 KiB
Python
169 lines
5.8 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
Exemple d'intégration de l'extracteur d'images HTML dans un flux de traitement de ticket.
|
|
Ce script montre comment utiliser l'extracteur d'images HTML comme une étape dans un processus
|
|
d'analyse de tickets, par exemple dans un orchestrateur ou un analyseur de tickets.
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import json
|
|
import logging
|
|
from typing import Dict, Any, List
|
|
|
|
# Ajouter le répertoire parent au chemin de recherche
|
|
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..'))
|
|
sys.path.append(parent_dir)
|
|
|
|
# Importer l'extracteur d'images HTML
|
|
from utils.image_extractor import extract_images_from_ticket
|
|
from utils.image_extractor.extract_all_images import enhance_ticket_data_with_images
|
|
|
|
def setup_logging():
|
|
"""Configure la journalisation."""
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
datefmt='%Y-%m-%d %H:%M:%S'
|
|
)
|
|
|
|
def process_ticket(ticket_dir: str) -> Dict[str, Any]:
|
|
"""
|
|
Exemple de fonction qui traite un ticket complet.
|
|
|
|
Args:
|
|
ticket_dir: Répertoire contenant les données du ticket
|
|
|
|
Returns:
|
|
Données du ticket enrichies
|
|
"""
|
|
logging.info(f"Traitement du ticket dans: {ticket_dir}")
|
|
|
|
# 1. Charger les informations de base du ticket
|
|
ticket_data = load_ticket_data(ticket_dir)
|
|
|
|
# 2. Extraire les images HTML
|
|
logging.info("Extraction des images intégrées dans le HTML...")
|
|
html_images = extract_images_from_ticket(ticket_dir)
|
|
|
|
# 3. Enrichir les données du ticket avec toutes les images
|
|
ticket_data["ticket_dir"] = ticket_dir
|
|
enhanced_data = enhance_ticket_data_with_images(ticket_data)
|
|
|
|
# 4. Ajouter des statistiques sur les images
|
|
stats = enhanced_data.get("images_stats", {})
|
|
logging.info(f"Images trouvées: {stats.get('total', 0)} total, " +
|
|
f"{stats.get('standard', 0)} standard, " +
|
|
f"{stats.get('embedded', 0)} intégrées")
|
|
|
|
# 5. Hypothétiquement, effectuer une analyse des images
|
|
analyze_images(enhanced_data.get("images", []))
|
|
|
|
return enhanced_data
|
|
|
|
def load_ticket_data(ticket_dir: str) -> Dict[str, Any]:
|
|
"""
|
|
Charge les données du ticket depuis les fichiers JSON.
|
|
|
|
Args:
|
|
ticket_dir: Répertoire contenant les données du ticket
|
|
|
|
Returns:
|
|
Données du ticket chargées
|
|
"""
|
|
ticket_data = {}
|
|
|
|
# Charger les informations du ticket
|
|
ticket_info_path = os.path.join(ticket_dir, "ticket_info.json")
|
|
if os.path.exists(ticket_info_path):
|
|
with open(ticket_info_path, 'r', encoding='utf-8') as f:
|
|
ticket_data["ticket_info"] = json.load(f)
|
|
|
|
# Charger le résumé du ticket
|
|
ticket_summary_path = os.path.join(ticket_dir, "ticket_summary.json")
|
|
if os.path.exists(ticket_summary_path):
|
|
with open(ticket_summary_path, 'r', encoding='utf-8') as f:
|
|
ticket_data["ticket_summary"] = json.load(f)
|
|
|
|
# Charger les pièces jointes
|
|
attachments_path = os.path.join(ticket_dir, "attachments_info.json")
|
|
if os.path.exists(attachments_path):
|
|
with open(attachments_path, 'r', encoding='utf-8') as f:
|
|
ticket_data["attachments"] = json.load(f)
|
|
|
|
# Charger les messages
|
|
messages_path = os.path.join(ticket_dir, "all_messages.json")
|
|
if os.path.exists(messages_path):
|
|
with open(messages_path, 'r', encoding='utf-8') as f:
|
|
ticket_data["messages"] = json.load(f)
|
|
|
|
return ticket_data
|
|
|
|
def analyze_images(image_paths: List[str]):
|
|
"""
|
|
Exemple de fonction qui analyse les images d'un ticket.
|
|
Cette fonction pourrait utiliser un modèle de vision ou une API externe.
|
|
|
|
Args:
|
|
image_paths: Liste des chemins d'images à analyser
|
|
"""
|
|
logging.info(f"Analyse de {len(image_paths)} images...")
|
|
|
|
# Simuler une analyse d'images
|
|
for i, img_path in enumerate(image_paths):
|
|
if os.path.exists(img_path):
|
|
logging.info(f" Analyse de l'image {i+1}: {os.path.basename(img_path)}")
|
|
# TODO: Intégrer votre logique d'analyse d'image ici
|
|
|
|
def save_results(ticket_data: Dict[str, Any], output_file: str):
|
|
"""
|
|
Sauvegarde les résultats de l'analyse.
|
|
|
|
Args:
|
|
ticket_data: Données du ticket à sauvegarder
|
|
output_file: Chemin du fichier de sortie
|
|
"""
|
|
# Créer le répertoire de sortie si nécessaire
|
|
output_dir = os.path.dirname(output_file)
|
|
if output_dir and not os.path.exists(output_dir):
|
|
os.makedirs(output_dir, exist_ok=True)
|
|
|
|
# Sauvegarder les résultats
|
|
with open(output_file, 'w', encoding='utf-8') as f:
|
|
json.dump(ticket_data, f, indent=2, ensure_ascii=False)
|
|
|
|
logging.info(f"Résultats sauvegardés dans: {output_file}")
|
|
|
|
def main():
|
|
"""Fonction principale."""
|
|
# Configurer la journalisation
|
|
setup_logging()
|
|
|
|
# Récupérer le chemin du répertoire de ticket
|
|
if len(sys.argv) > 1:
|
|
ticket_dir = sys.argv[1]
|
|
else:
|
|
# Utiliser un répertoire de test par défaut
|
|
ticket_dir = os.path.join(parent_dir, "output", "ticket_T0241", "T0241_20250409_141018")
|
|
|
|
# Vérifier que le répertoire existe
|
|
if not os.path.exists(ticket_dir):
|
|
logging.error(f"Répertoire introuvable: {ticket_dir}")
|
|
sys.exit(1)
|
|
|
|
# Traiter le ticket
|
|
ticket_data = process_ticket(ticket_dir)
|
|
|
|
# Sauvegarder les résultats
|
|
output_file = os.path.join(ticket_dir, "ticket_analysis.json")
|
|
save_results(ticket_data, output_file)
|
|
|
|
# Afficher un résumé
|
|
ticket_code = ticket_data.get("ticket_summary", {}).get("code", os.path.basename(ticket_dir))
|
|
print(f"\nAnalyse du ticket {ticket_code} terminée.")
|
|
print(f"Résultats sauvegardés dans: {output_file}")
|
|
|
|
if __name__ == "__main__":
|
|
main() |