File size: 4,024 Bytes
1eb76aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8a0185
 
1eb76aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/env python3
"""
Interface Gradio : Transcription médicale → Correction → Matching → Rapport
"""
import gradio as gr
import sys
import os

# Fix pour le problème de pickle avec TemplateInfo
import template_db_creation
sys.modules['__main__'].TemplateInfo = template_db_creation.TemplateInfo

from template_db_creation import MedicalTemplateParser
from smart_match import TranscriptionMatcher
from correcteur import MedicalTranscriptionProcessor, AZURE_OPENAI_DEPLOYMENT

# Chemin hardcodé vers la base de données
#DB_PATH = "/Users/macbook/medical-agent/medical-agent/templates/medical_templates.pkl"
DB_PATH ="templates/medical_templates.pkl"
# Variables globales
parser = None
matcher = None

def initialize_system():
    """Initialise le système au démarrage"""
    global parser, matcher
    
    try:
        print(f"📂 Chargement de la base de données: {DB_PATH}")
        parser = MedicalTemplateParser()
        parser.load_database(DB_PATH)
        
        matcher = TranscriptionMatcher(parser)
        
        print(f"✅ Système initialisé avec {len(parser.templates)} templates")
        return True
    except Exception as e:
        print(f"❌ Erreur initialisation: {e}")
        return False

def process_transcription(transcription: str):
    """
    Traite la transcription médicale complète
    
    Args:
        transcription: Texte de la transcription
        
    Returns:
        Tuple (transcription_corrigée, template_vide, rapport_final)
    """
    try:
        # Étape 1: Correction ASR
        print("🔧 Étape 1: Correction de la transcription...")
        processor = MedicalTranscriptionProcessor(AZURE_OPENAI_DEPLOYMENT)
        result = processor.process_transcription(transcription)
        corrected_transcription = result.final_corrected_text
        
        # Étape 2: Matching et remplissage du template
        print("🔍 Étape 2: Recherche du template approprié...")
        results = matcher.match_and_fill(corrected_transcription, return_top_k=1)
        
        if not results:
            return (
                corrected_transcription,
                "❌ Aucun template approprié trouvé",
                "❌ Impossible de générer le rapport"
            )
        
        best_result = results[0]
        
        # Préparer le template vide avec toutes les informations
        template_vide = f"{best_result.template_id}\n"
        template_vide += "=" * len(best_result.template_id) + "\n"
        template_vide += best_result.template_content
        
        # Préparer le rapport final rempli avec toutes les sections
        rapport_final = f"{best_result.template_id}\n"
        rapport_final += "=" * len(best_result.template_id) + "\n"
        
        # Ajouter toutes les sections remplies
        rapport_final += best_result.filled_template

        
        print(f"✅ Traitement terminé - Template: {best_result.template_id}")
        
        return corrected_transcription, template_vide, rapport_final
        
    except Exception as e:
        error_msg = f"❌ Erreur: {str(e)}"
        print(error_msg)
        return error_msg, "", ""

# Initialiser le système au démarrage
print("🚀 Initialisation du système...")
if not initialize_system():
    print("⚠️ Erreur lors de l'initialisation - vérifiez le chemin de la DB")

# Interface Gradio
demo = gr.Interface(
    fn=process_transcription,
    inputs=gr.Textbox(
        lines=15, 
        label="📝 Transcription médicale",
        placeholder="Collez ici la transcription de l'examen médical..."
    ),
    outputs=[
        gr.Textbox(lines=20, label="✅ Transcription corrigée", show_copy_button=True),
        gr.Textbox(lines=20, label="📋 Rapport à remplir (Template)", show_copy_button=True),
        gr.Textbox(lines=20, label="📄 Compte-rendu structuré final", show_copy_button=True),
    ],
    title="🏥 Génération de comptes-rendus structurés",

)

if __name__ == "__main__":
    demo.launch(share=True)