import torch import torch.nn as nn import timm import numpy as np import mediapipe as mp from mediapipe.tasks import python from mediapipe.tasks.python import vision from PIL import Image from torchvision import transforms import gradio as gr import os import sys # --- 1. Architectural Configuration (Cloud-Rigid) --- MODEL_NAME = 'mobilenetv3_large_100' EXPERT_NAME = 'vit_base_patch16_224' SPECIALIST_WEIGHTS = 'model_asher_mcdade_split_heads.pth' EXPERT_WEIGHTS = 'model_geometry_expert_transformer.pth' LANDMARKER_PATH = "face_landmarker.task" DEVICE = 'cpu' # Free tier HF Spaces run on CPU # --- 2. Hybrid Model Definition (STRICT WEIGHT SYNC) --- class HybridSplitHeadMobileNet(nn.Module): def __init__(self, model_name): super(HybridSplitHeadMobileNet, self).__init__() self.backbone = timm.create_model(model_name, pretrained=False) self.feature_dim = self.backbone.classifier.in_features self.backbone.classifier = nn.Identity() self.combined_dim = self.feature_dim + 5 self.frontal_head = nn.Sequential( nn.Linear(self.combined_dim, 128), nn.BatchNorm1d(128), nn.ReLU(), nn.Dropout(0.5), nn.Linear(128, 3) ) self.lateral_head = nn.Sequential( nn.Linear(self.combined_dim, 128), nn.BatchNorm1d(128), nn.ReLU(), nn.Dropout(0.5), nn.Linear(128, 1) ) def forward_front(self, img, priors): x = torch.cat((self.backbone(img), priors), dim=1) return self.frontal_head(x) def forward_side(self, img, priors): x = torch.cat((self.backbone(img), priors), dim=1) return self.lateral_head(x) # --- 3. System Initialization --- print("--- Initializing Clinical Engine Foundations ---") # A. Load Specialist (The Scorer) specialist = HybridSplitHeadMobileNet(MODEL_NAME) if os.path.exists(SPECIALIST_WEIGHTS): specialist.load_state_dict(torch.load(SPECIALIST_WEIGHTS, map_location='cpu', weights_only=True)) specialist.eval() # B. Load Anatomy Expert (The Prior Provider) expert = timm.create_model(EXPERT_NAME, pretrained=False) expert.head = nn.Linear(expert.head.in_features, 5) if os.path.exists(EXPERT_WEIGHTS): expert.load_state_dict(torch.load(EXPERT_WEIGHTS, map_location='cpu', weights_only=True)) expert.eval() else: expert = None print("Warning: Expert Weights missing. Fallback to Neutral Priors only.") # C. Initialize MediaPipe if os.path.exists(LANDMARKER_PATH): base_options = python.BaseOptions(model_asset_path=LANDMARKER_PATH) detector = vision.FaceLandmarker.create_from_options(vision.FaceLandmarkerOptions(base_options=base_options, num_faces=1)) else: detector = None # Transforms main_transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) expert_transform = transforms.Compose([ transforms.Resize(224), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]) ]) # --- 4. Prediction Logic --- def get_priors(pil_img): try: mp_img = mp.Image(image_format=mp.ImageFormat.SRGB, data=np.array(pil_img)) res = detector.detect(mp_img) if res.face_landmarks: l = res.face_landmarks[0] def dist(p1, p2): return np.sqrt((p1.x-p2.x)**2 + (p1.y-p2.y)**2) w = dist(l[234], l[454]) priors = [dist(l[278], l[48])/w, dist(l[13], l[14])/w, dist(l[14], l[17])/w, 0.6, dist(l[168], l[4])/w] return torch.tensor([priors], dtype=torch.float32) except: pass if expert is not None: with torch.no_grad(): return expert(expert_transform(pil_img).unsqueeze(0)) return torch.tensor([[0.28, 0.08, 0.12, 0.65, 0.35]], dtype=torch.float32) def predict(front_img, side_img): if front_img is None or side_img is None: return None with torch.no_grad(): f_p = get_priors(front_img) s_p = get_priors(side_img) f_t = main_transform(front_img).unsqueeze(0) s_t = main_transform(side_img).unsqueeze(0) f_res = specialist.forward_front(f_t, f_p).numpy()[0] s_res = specialist.forward_side(s_t, s_p).numpy()[0] scores = { "Nasal Form": float(np.clip(f_res[0], 1, 5)), "Nasal Deviation": float(np.clip(f_res[1], 1, 5)), "Vermillion Border": float(np.clip(f_res[2], 1, 5)), "Nasal Profile": float(np.clip(s_res[0], 1, 5)) } # Returning Raw JSON Object for Clean UI Rendering return scores # --- 5. UI Build --- with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("# Asher-McDade Cleft Assessment AI") gr.Markdown("Direct clinical assessment tool for surgical outcome analysis.") with gr.Row(): with gr.Column(): input_front = gr.Image(type="pil", label="Frontal View") input_side = gr.Image(type="pil", label="Lateral View") btn = gr.Button("Generate Clinical Scores", variant="primary") with gr.Column(): # Use gr.JSON for raw data visualization output_json = gr.JSON(label="Clinical Assessment Results") gr.Markdown("**Scale Guide:** 1: Normal Appearance | 5: Severe Distortion") btn.click(fn=predict, inputs=[input_front, input_side], outputs=output_json) if __name__ == "__main__": demo.launch()