|
|
""" |
|
|
main.py |
|
|
Point d'entrée principal pour le système de matching hybride |
|
|
""" |
|
|
|
|
|
import os |
|
|
import sys |
|
|
import logging |
|
|
from pathlib import Path |
|
|
|
|
|
|
|
|
from template_db_creation import MedicalTemplateParser,TemplateInfo |
|
|
from smart_match import TranscriptionMatcher |
|
|
from title_matcher import HybridMatcher |
|
|
|
|
|
|
|
|
logging.basicConfig( |
|
|
level=logging.INFO, |
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' |
|
|
) |
|
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
|
|
|
def load_transcription_file(filepath: str) -> tuple: |
|
|
""" |
|
|
Charge une transcription depuis un fichier |
|
|
|
|
|
Args: |
|
|
filepath: Chemin vers le fichier |
|
|
|
|
|
Returns: |
|
|
tuple: (contenu, nom_fichier) |
|
|
""" |
|
|
try: |
|
|
with open(filepath, 'r', encoding='utf-8') as f: |
|
|
content = f.read() |
|
|
filename = os.path.basename(filepath) |
|
|
logger.info(f"✅ Transcription chargée: {filename}") |
|
|
return content, filename |
|
|
except Exception as e: |
|
|
logger.error(f"❌ Erreur lecture fichier: {e}") |
|
|
return None, None |
|
|
|
|
|
|
|
|
def save_result(result, output_path: str): |
|
|
""" |
|
|
Sauvegarde le résultat dans un fichier |
|
|
|
|
|
Args: |
|
|
result: MatchResult à sauvegarder |
|
|
output_path: Chemin du fichier de sortie |
|
|
""" |
|
|
try: |
|
|
with open(output_path, 'w', encoding='utf-8') as f: |
|
|
f.write("="*80 + "\n") |
|
|
f.write(f"TEMPLATE: {result.template_id}\n") |
|
|
f.write(f"MÉTHODE: {result.match_method}\n") |
|
|
f.write(f"CONFIANCE: {result.confidence_score:.2%}\n") |
|
|
f.write("="*80 + "\n\n") |
|
|
f.write(result.filled_template) |
|
|
logger.info(f"✅ Résultat sauvegardé: {output_path}") |
|
|
except Exception as e: |
|
|
logger.error(f"❌ Erreur sauvegarde: {e}") |
|
|
|
|
|
|
|
|
def batch_process_directory(hybrid_matcher, input_dir: str, output_dir: str): |
|
|
""" |
|
|
Traite tous les fichiers d'un répertoire |
|
|
|
|
|
Args: |
|
|
hybrid_matcher: Instance de HybridMatcher |
|
|
input_dir: Répertoire des transcriptions |
|
|
output_dir: Répertoire de sortie |
|
|
""" |
|
|
|
|
|
os.makedirs(output_dir, exist_ok=True) |
|
|
|
|
|
|
|
|
input_path = Path(input_dir) |
|
|
transcription_files = list(input_path.glob("*.txt")) + list(input_path.glob("*.rtf")) |
|
|
|
|
|
logger.info(f"\n{'='*80}") |
|
|
logger.info(f"📁 TRAITEMENT PAR LOT - {len(transcription_files)} fichiers") |
|
|
logger.info(f"{'='*80}\n") |
|
|
|
|
|
results_summary = [] |
|
|
|
|
|
for i, filepath in enumerate(transcription_files, 1): |
|
|
logger.info(f"\n{'─'*80}") |
|
|
logger.info(f"📄 Fichier {i}/{len(transcription_files)}: {filepath.name}") |
|
|
logger.info(f"{'─'*80}") |
|
|
|
|
|
|
|
|
content, filename = load_transcription_file(str(filepath)) |
|
|
if not content: |
|
|
continue |
|
|
|
|
|
|
|
|
results = hybrid_matcher.match_and_fill( |
|
|
transcription=content, |
|
|
transcription_filename=filename |
|
|
) |
|
|
|
|
|
if results: |
|
|
result = results[0] |
|
|
|
|
|
|
|
|
output_filename = f"{filepath.stem}_filled.txt" |
|
|
output_path = os.path.join(output_dir, output_filename) |
|
|
save_result(result, output_path) |
|
|
|
|
|
|
|
|
results_summary.append({ |
|
|
'filename': filename, |
|
|
'template': result.template_id, |
|
|
'method': result.match_method, |
|
|
'confidence': result.confidence_score |
|
|
}) |
|
|
else: |
|
|
logger.warning(f"⚠️ Aucun résultat pour {filename}") |
|
|
results_summary.append({ |
|
|
'filename': filename, |
|
|
'template': 'NONE', |
|
|
'method': 'FAILED', |
|
|
'confidence': 0.0 |
|
|
}) |
|
|
|
|
|
|
|
|
print("\n" + "="*80) |
|
|
print("📊 RÉSUMÉ DU TRAITEMENT PAR LOT") |
|
|
print("="*80) |
|
|
for item in results_summary: |
|
|
print(f"📄 {item['filename']}") |
|
|
print(f" → Template: {item['template']}") |
|
|
print(f" → Méthode: {item['method']}") |
|
|
print(f" → Confiance: {item['confidence']:.2%}") |
|
|
print() |
|
|
|
|
|
|
|
|
def interactive_mode(hybrid_matcher): |
|
|
""" |
|
|
Mode interactif pour traiter les transcriptions |
|
|
|
|
|
Args: |
|
|
hybrid_matcher: Instance de HybridMatcher |
|
|
""" |
|
|
|
|
|
transcription_example = """ |
|
|
IRM pelvienne. Indication clinique. Technique. Acquisition sagittale, axiale et coronale T2, saturation axiale, diffusion axiale T1. Résultats. Présence d'un utérus antéversé médio-pelvien dont le grand axe mesure 72 mm sur 40 mm sur 40 mm. La zone jonctionnelle apparaît floue. Elle est épaissie de façon diffuse, asymétrique, avec une atteinte de plus de 50% de l'épaisseur du myomètre et comporte des spots en hypersignal T2, l'ensemble traduisant une adénomyose. |
|
|
Pas d'épaississement cervical. À noter la présence d'un petit kyste liquidien de type Naboth. |
|
|
Les 2 ovaires sont repérés, porteurs de formations folliculaires communes en hypersignal homogène T2 de petite taille. L'ovaire droit mesure 30 x 25 mm. L'ovaire gauche mesure 25 x 23 mm. Pas d'épanchement dans le cul-de-sac de Douglas. |
|
|
Absence de foyer d'endométriose profonde. Conclusion. |
|
|
Aspect d'adénomyose diffuse, symétrique, profonde. |
|
|
Pas d'épaississement endométrial. Absence d'endométriome. Absence d'épanchement dans le cul-de-sac de Douglas. |
|
|
""" |
|
|
|
|
|
while True: |
|
|
print("\n" + "="*80) |
|
|
print("🔧 MODE INTERACTIF - OPTIONS") |
|
|
print("="*80) |
|
|
print("1. Charger une transcription depuis un fichier (avec matching par titre)") |
|
|
print("2. Entrer une transcription manuellement (matching sémantique uniquement)") |
|
|
print("3. Utiliser l'exemple de transcription (matching sémantique)") |
|
|
print("4. Traitement par lot d'un répertoire") |
|
|
print("5. Quitter") |
|
|
print("="*80) |
|
|
|
|
|
choice = input("\n👉 Votre choix: ").strip() |
|
|
|
|
|
if choice == "1": |
|
|
|
|
|
filepath = input("📂 Chemin du fichier de transcription: ").strip() |
|
|
|
|
|
if not os.path.exists(filepath): |
|
|
print(f"❌ Fichier introuvable: {filepath}") |
|
|
continue |
|
|
|
|
|
content, filename = load_transcription_file(filepath) |
|
|
if not content: |
|
|
continue |
|
|
|
|
|
|
|
|
results = hybrid_matcher.match_and_fill( |
|
|
transcription=content, |
|
|
transcription_filename=filename |
|
|
) |
|
|
|
|
|
elif choice == "2": |
|
|
|
|
|
print("\n📝 Entrez la transcription (Ctrl+D ou Ctrl+Z pour terminer):") |
|
|
lines = [] |
|
|
try: |
|
|
while True: |
|
|
line = input() |
|
|
lines.append(line) |
|
|
except EOFError: |
|
|
pass |
|
|
|
|
|
content = "\n".join(lines) |
|
|
if not content.strip(): |
|
|
print("❌ Transcription vide") |
|
|
continue |
|
|
|
|
|
|
|
|
results = hybrid_matcher.match_and_fill( |
|
|
transcription=content, |
|
|
transcription_filename=None |
|
|
) |
|
|
|
|
|
elif choice == "3": |
|
|
|
|
|
content = transcription_example |
|
|
|
|
|
|
|
|
results = hybrid_matcher.match_and_fill( |
|
|
transcription=content, |
|
|
transcription_filename=None |
|
|
) |
|
|
|
|
|
elif choice == "4": |
|
|
|
|
|
input_dir = input("📂 Répertoire des transcriptions: ").strip() |
|
|
if not os.path.exists(input_dir): |
|
|
print(f"❌ Répertoire introuvable: {input_dir}") |
|
|
continue |
|
|
|
|
|
output_dir = input("📂 Répertoire de sortie: ").strip() |
|
|
|
|
|
batch_process_directory(hybrid_matcher, input_dir, output_dir) |
|
|
continue |
|
|
|
|
|
elif choice == "5": |
|
|
print("\n👋 Au revoir!") |
|
|
break |
|
|
|
|
|
else: |
|
|
print("❌ Choix invalide") |
|
|
continue |
|
|
|
|
|
|
|
|
if results: |
|
|
for i, result in enumerate(results, 1): |
|
|
print(f"\n{'#'*80}") |
|
|
print(f"# RÉSULTAT {i}/{len(results)}") |
|
|
print(f"{'#'*80}") |
|
|
hybrid_matcher.semantic_matcher.display_result(result) |
|
|
|
|
|
|
|
|
save_choice = input("\n💾 Sauvegarder le résultat? (o/n): ").strip().lower() |
|
|
if save_choice == 'o': |
|
|
output_file = input("📄 Nom du fichier de sortie: ").strip() |
|
|
if output_file: |
|
|
save_result(results[0], output_file) |
|
|
else: |
|
|
print("❌ Aucun résultat trouvé") |
|
|
|
|
|
|
|
|
def main(): |
|
|
""" |
|
|
Fonction principale |
|
|
""" |
|
|
print("\n" + "="*80) |
|
|
print("🏥 SYSTÈME DE MATCHING HYBRIDE DE TEMPLATES MÉDICAUX") |
|
|
print("="*80) |
|
|
print("Version 2.0 - Matching par titre + Matching sémantique") |
|
|
print("="*80 + "\n") |
|
|
|
|
|
|
|
|
db_path = input("📂 Chemin vers la base de données (.pkl): ").strip() |
|
|
|
|
|
if not os.path.exists(db_path): |
|
|
print(f"❌ Fichier introuvable: {db_path}") |
|
|
return |
|
|
|
|
|
print("\n🔄 Chargement de la base de données...") |
|
|
parser = MedicalTemplateParser() |
|
|
|
|
|
try: |
|
|
parser.load_database(db_path) |
|
|
print(f"✅ Base chargée: {len(parser.templates)} templates disponibles") |
|
|
except Exception as e: |
|
|
print(f"❌ Erreur lors du chargement: {e}") |
|
|
return |
|
|
|
|
|
|
|
|
print("\n🔄 Initialisation des matchers...") |
|
|
|
|
|
try: |
|
|
semantic_matcher = TranscriptionMatcher(parser) |
|
|
print("✅ Matcher sémantique initialisé") |
|
|
|
|
|
hybrid_matcher = HybridMatcher(parser, semantic_matcher) |
|
|
print("✅ Matcher hybride initialisé") |
|
|
except Exception as e: |
|
|
print(f"❌ Erreur lors de l'initialisation: {e}") |
|
|
return |
|
|
|
|
|
|
|
|
if not semantic_matcher.llm: |
|
|
print("\n⚠️ ATTENTION: GPT n'est pas disponible") |
|
|
print("⚠️ Vérifiez que OPENAI_API_KEY est définie") |
|
|
print("⚠️ Le remplissage sera basique") |
|
|
|
|
|
continue_choice = input("\nContinuer quand même? (o/n): ").strip().lower() |
|
|
if continue_choice != 'o': |
|
|
return |
|
|
|
|
|
|
|
|
print("\n" + "="*80) |
|
|
print("📊 STATISTIQUES DE LA BASE") |
|
|
print("="*80) |
|
|
|
|
|
|
|
|
types_count = {} |
|
|
for template_id, template_info in parser.templates.items(): |
|
|
template_type = template_info.type |
|
|
types_count[template_type] = types_count.get(template_type, 0) + 1 |
|
|
|
|
|
print(f"📋 Total de templates: {len(parser.templates)}") |
|
|
print("\n📑 Répartition par type:") |
|
|
for template_type, count in sorted(types_count.items(), key=lambda x: x[1], reverse=True): |
|
|
print(f" • {template_type}: {count}") |
|
|
|
|
|
print("="*80) |
|
|
|
|
|
|
|
|
print("\n" + "="*80) |
|
|
print("🔧 MODE DE FONCTIONNEMENT") |
|
|
print("="*80) |
|
|
print("1. Mode interactif (traiter des transcriptions une par une)") |
|
|
print("2. Traitement par lot (traiter un répertoire entier)") |
|
|
print("3. Quitter") |
|
|
print("="*80) |
|
|
|
|
|
mode_choice = input("\n👉 Votre choix: ").strip() |
|
|
|
|
|
if mode_choice == "1": |
|
|
interactive_mode(hybrid_matcher) |
|
|
elif mode_choice == "2": |
|
|
input_dir = input("\n📂 Répertoire des transcriptions: ").strip() |
|
|
if not os.path.exists(input_dir): |
|
|
print(f"❌ Répertoire introuvable: {input_dir}") |
|
|
return |
|
|
|
|
|
output_dir = input("📂 Répertoire de sortie: ").strip() |
|
|
batch_process_directory(hybrid_matcher, input_dir, output_dir) |
|
|
elif mode_choice == "3": |
|
|
print("\n👋 Au revoir!") |
|
|
else: |
|
|
print("❌ Choix invalide") |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
try: |
|
|
main() |
|
|
except KeyboardInterrupt: |
|
|
print("\n\n👋 Interruption par l'utilisateur. Au revoir!") |
|
|
sys.exit(0) |
|
|
except Exception as e: |
|
|
logger.error(f"❌ Erreur fatale: {e}", exc_info=True) |
|
|
sys.exit(1) |
|
|
|