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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import torch
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from health_multimodal.image.inference_engine import ImageInferenceEngine
|
| 5 |
+
from health_multimodal.image.model.pretrained import get_biovil_t_image_encoder
|
| 6 |
+
from health_multimodal.image.data.transforms import create_chest_xray_transform_for_inference
|
| 7 |
+
from transformers import AutoModel, AutoTokenizer
|
| 8 |
+
import streamlit as st
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import math
|
| 11 |
+
|
| 12 |
+
# 1. Configuration de la page
|
| 13 |
+
st.set_page_config(page_title="MIROIR", layout="wide")
|
| 14 |
+
st.markdown("### 🩺 MIROIR : Modèle d'Intelligence pour le Rapprochement d'Observations, d'Images et de Rapports")
|
| 15 |
+
|
| 16 |
+
# 2. Mise en cache du chargement du modèle pour éviter de le recharger à chaque interaction
|
| 17 |
+
@st.cache_resource
|
| 18 |
+
def load_models():
|
| 19 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 20 |
+
|
| 21 |
+
# Configuration des encodeurs d'images basés sur BioViL-T
|
| 22 |
+
image_encoder = get_biovil_t_image_encoder()
|
| 23 |
+
transform = create_chest_xray_transform_for_inference(resize=512, center_crop_size=448)
|
| 24 |
+
|
| 25 |
+
image_inference_engine = ImageInferenceEngine(image_encoder, transform)
|
| 26 |
+
|
| 27 |
+
# Configuration des encodeurs de textes
|
| 28 |
+
tokenizer = AutoTokenizer.from_pretrained("microsoft/BiomedVLP-BioViL-T", trust_remote_code=True)
|
| 29 |
+
text_model = AutoModel.from_pretrained("microsoft/BiomedVLP-BioViL-T", trust_remote_code=True).to(device)
|
| 30 |
+
text_model.eval()
|
| 31 |
+
|
| 32 |
+
return image_inference_engine, tokenizer, text_model, device
|
| 33 |
+
|
| 34 |
+
# 3. Chargement modèle
|
| 35 |
+
image_engine, tokenizer, text_model, device = load_models()
|
| 36 |
+
|
| 37 |
+
# 4. Fonction pour calculer le score de similarité cosinus
|
| 38 |
+
def compute_similarity(image_path, text_content):
|
| 39 |
+
local_device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
path_object = Path(image_path)
|
| 43 |
+
|
| 44 |
+
with torch.no_grad():
|
| 45 |
+
image_embedding = image_engine.get_projected_global_embedding(path_object)
|
| 46 |
+
|
| 47 |
+
if not isinstance(image_embedding, torch.Tensor):
|
| 48 |
+
image_embedding = torch.tensor(image_embedding).to(local_device)
|
| 49 |
+
else:
|
| 50 |
+
image_embedding = image_embedding.to(local_device)
|
| 51 |
+
|
| 52 |
+
if image_embedding.ndim == 1:
|
| 53 |
+
image_embedding = image_embedding.unsqueeze(0)
|
| 54 |
+
|
| 55 |
+
image_embedding = image_embedding / image_embedding.norm(dim=-1, keepdim=True)
|
| 56 |
+
|
| 57 |
+
inputs = tokenizer(text_content, return_tensors="pt", padding="max_length", truncation=True, max_length=512).to(local_device)
|
| 58 |
+
|
| 59 |
+
with torch.no_grad():
|
| 60 |
+
text_embedding = text_model.get_projected_text_embeddings(
|
| 61 |
+
input_ids=inputs["input_ids"],
|
| 62 |
+
attention_mask=inputs["attention_mask"]
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
if text_embedding.ndim == 1:
|
| 66 |
+
text_embedding = text_embedding.unsqueeze(0)
|
| 67 |
+
|
| 68 |
+
text_embedding = text_embedding / text_embedding.norm(dim=-1, keepdim=True)
|
| 69 |
+
|
| 70 |
+
similarity = torch.mm(image_embedding, text_embedding.t()).item()
|
| 71 |
+
|
| 72 |
+
similarity_prob = 1 / (1 + math.exp(-similarity * 4)) # Le multiplicateur (ex: 4) ajuste la sensibilité
|
| 73 |
+
return similarity_prob
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
except Exception as e:
|
| 77 |
+
st.error(f"Erreur lors du calcul : {e}")
|
| 78 |
+
return 0.0
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if "current_pair" not in st.session_state:
|
| 82 |
+
st.session_state.current_pair = None
|
| 83 |
+
st.session_state.pair_type = None
|
| 84 |
+
|
| 85 |
+
col_btn1, col_btn2 = st.columns(2)
|
| 86 |
+
|
| 87 |
+
with col_btn1:
|
| 88 |
+
if st.button("✅ Exemple une paire CORRECTE (Match)", use_container_width=True):
|
| 89 |
+
df_pos = pd.read_csv("./chexpert_matches_sample.csv", index_col=0)
|
| 90 |
+
st.session_state.current_pair = df_pos.sample(1).iloc[0]
|
| 91 |
+
st.session_state.pair_type = "Correcte (Match)"
|
| 92 |
+
|
| 93 |
+
with col_btn2:
|
| 94 |
+
if st.button("❌ Exemple d'une paire INCORRECTE (Mismatch)", use_container_width=True):
|
| 95 |
+
df_neg = pd.read_csv("./chexpert_mismatches_swapping_2.csv", index_col=0)
|
| 96 |
+
st.session_state.current_pair = df_neg.sample(1).iloc[0]
|
| 97 |
+
st.session_state.pair_type = "Incorrecte (Mismatch)"
|
| 98 |
+
|
| 99 |
+
if st.session_state.current_pair is not None:
|
| 100 |
+
pair = st.session_state.current_pair
|
| 101 |
+
|
| 102 |
+
st.info(f"Source actuelle : Paire **{st.session_state.pair_type}**")
|
| 103 |
+
|
| 104 |
+
col1, col2 = st.columns([0.6, 1.4])
|
| 105 |
+
with col1:
|
| 106 |
+
st.markdown("#### 🖼️ Radiographie Thoracique :")
|
| 107 |
+
img_source = st.radio("Source de l'image :", ["Image originale de la paire", "Uploader une autre image"])
|
| 108 |
+
|
| 109 |
+
image_to_process = None
|
| 110 |
+
if img_source == "Image originale de la paire":
|
| 111 |
+
image_path = "CheXpert/CheXpert-v1.0-small/"+pair["path_to_image"]
|
| 112 |
+
st.caption(f"Chemin de l'image : `{image_path}`")
|
| 113 |
+
try:
|
| 114 |
+
image_to_process = image_path
|
| 115 |
+
img_display = Image.open(image_path)
|
| 116 |
+
st.image(img_display, use_container_width=250)
|
| 117 |
+
except FileNotFoundError:
|
| 118 |
+
st.warning("Fichier image introuvable localement. Veuillez uploader une image manuellement ci-dessous.")
|
| 119 |
+
img_source = "Uploader une autre image"
|
| 120 |
+
|
| 121 |
+
if img_source == "Uploader une autre image":
|
| 122 |
+
uploaded_file = st.file_uploader("Choisissez une radiographie (JPG/PNG)", type=["jpg", "jpeg", "png"])
|
| 123 |
+
if uploaded_file is not None:
|
| 124 |
+
img_display = Image.open(uploaded_file)
|
| 125 |
+
st.image(img_display, use_container_width=250)
|
| 126 |
+
image_to_process = "temp_uploaded_img.jpg"
|
| 127 |
+
img_display.convert("RGB").save(image_to_process)
|
| 128 |
+
|
| 129 |
+
with col2:
|
| 130 |
+
st.markdown("#### 📝 Compte Rendu (Éditables en direct) :")
|
| 131 |
+
|
| 132 |
+
default_text = pair["section_impression"] if pd.notna(pair["section_impression"]) else pair["report"]
|
| 133 |
+
|
| 134 |
+
edited_text = st.text_area(
|
| 135 |
+
"Modifiez le texte ci-dessous pour voir le score changer instantanément :",
|
| 136 |
+
value=str(default_text),
|
| 137 |
+
height=300
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
if image_to_process is not None and edited_text:
|
| 142 |
+
with st.spinner("Calcul de la similarité..."):
|
| 143 |
+
score = compute_similarity(image_to_process, edited_text)
|
| 144 |
+
|
| 145 |
+
st.markdown("#### 📊 Score en direct :")
|
| 146 |
+
|
| 147 |
+
percentage = max(0.0, min(1.0, score)) * 100
|
| 148 |
+
|
| 149 |
+
custom_html = f"""
|
| 150 |
+
<div style="width: 100%; margin-top: 40px; margin-bottom: 10px; position: relative; font-family: sans-serif;">
|
| 151 |
+
<div style="width: 100%; height: 16px; background-color: #e0e4ec; border-radius: 8px; position: relative;">
|
| 152 |
+
|
| 153 |
+
<div style="width: {percentage}%; height: 100%; background: linear-gradient(90deg, #ff4b4b, #1f77b4); border-radius: 8px;"></div>
|
| 154 |
+
|
| 155 |
+
<div style="position: absolute; left: {percentage}%; top: -35px; transform: translateX(-50%); white-space: nowrap;">
|
| 156 |
+
<span style="font-size: 20px; font-weight: bold; color: #1f77b4; background-color: #ffffff; padding: 4px 10px; border-radius: 6px; border: 2px solid #1f77b4; box-shadow: 0px 2px 6px rgba(0,0,0,0.15);">
|
| 157 |
+
{score:.2f}
|
| 158 |
+
</span>
|
| 159 |
+
</div>
|
| 160 |
+
</div>
|
| 161 |
+
|
| 162 |
+
</div>
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
st.components.v1.html(custom_html, height=70)
|
| 166 |
+
st.write("") # Respiration visuelle
|
| 167 |
+
|
| 168 |
+
# 3. Affichage immédiat de la conclusion juste en dessous
|
| 169 |
+
if score >= 0.75:
|
| 170 |
+
st.success(f"🟢 **Excellente cohérence !** La radiographie et le compte rendu médical décrivent parfaitement les mêmes observations.")
|
| 171 |
+
|
| 172 |
+
elif 0.40 <= score < 0.75:
|
| 173 |
+
st.warning(f"⚠️ **Attention : Cohérence modérée.** Le texte a été modifié ou certaines observations du compte rendu ne semblent pas correspondre de manière flagrante aux structures identifiées sur l'image.")
|
| 174 |
+
|
| 175 |
+
else:
|
| 176 |
+
st.error(f"🚨 **ALERTE : Incohérence majeure !** Il y a une contradiction totale ou une absence de lien logique entre cette radiographie et le texte fourni. Risque d'erreur de diagnostic ou d'inversion de dossier patient.")
|
| 177 |
+
|
| 178 |
+
else:
|
| 179 |
+
st.info("Veuillez fournir une image et un texte valides pour calculer le score.")
|
| 180 |
+
|
| 181 |
+
else:
|
| 182 |
+
st.write("👈 Cliquez sur l'un des boutons ci-dessus pour charger une paire aléatoire de données.")
|
packages.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
git
|
| 2 |
+
git-lfs
|
| 3 |
+
ffmpeg
|
| 4 |
+
libsm6
|
| 5 |
+
libxext6
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
pandas
|
| 3 |
+
torch
|
| 4 |
+
pillow
|
| 5 |
+
transformers
|
| 6 |
+
git+https://github.com/microsoft/hi-ml.git#subdirectory=hi-ml-multimodal
|