import gradio as gr import torch from torchvision import transforms from PIL import Image, ImageDraw, ImageFont from transformers import ViTForImageClassification from safetensors import safe_open # 1. Cargar modelo ViT con el número correcto de clases model = ViTForImageClassification.from_pretrained( 'google/vit-base-patch16-224', num_labels=5, # 5 clases ignore_mismatched_sizes=True ) # 2. Cargar pesos entrenados try: state_dict = {} with safe_open('model.safetensors', framework="pt", device="cpu") as f: for key in f.keys(): state_dict[key] = f.get_tensor(key) model.load_state_dict(state_dict, strict=True) except Exception as e: raise Exception(f"Error al cargar los pesos del modelo: {str(e)}") model.eval() # Transformaciones transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) categories = ['H1', 'H2', 'H3', 'H5', 'H6'] def predict(image_path): try: # Preprocesamiento image = Image.open(image_path).convert('RGB') image_tensor = transform(image).unsqueeze(0) # Predicción with torch.no_grad(): outputs = model(image_tensor) probabilities = torch.nn.functional.softmax(outputs.logits[0], dim=0) predicted_class_index = torch.argmax(probabilities).item() predicted_class = categories[predicted_class_index] confidence = probabilities[predicted_class_index].item() # Texto simplificado (solo predicción principal) text = f"{predicted_class} ({confidence:.2%})" # Dibujar texto draw = ImageDraw.Draw(image) try: font_size = max(20, image.width // 15) font = ImageFont.truetype("arial.ttf", font_size) except IOError: font = ImageFont.load_default() # Posición bbox = draw.textbbox((0, 0), text, font=font) text_width = bbox[2] - bbox[0] margin = 15 x = image.width - text_width - margin y = margin # Fondo draw.rectangle( [(x - 5, y - 5), (x + text_width + 5, y + font_size + 5)], fill=(255, 255, 255, 180) ) # Texto draw.text((x, y), text, font=font, fill=(255, 0, 0)) return image except Exception as e: print(f"Error procesando imagen: {str(e)}") return None # Interfaz Gradio actualizada gr.Interface( fn=predict, inputs=gr.components.Image(type="filepath", label="Input Image"), outputs=gr.components.Image(type="pil", label="Classification Result"), title="Clasificador de Imágenes Microscópicas Fúngicas - ViT", description="Clasifica imágenes en las categorías H1, H2, H3, H5 o H6", examples=[ ["examples/H1_example.jpg"], ["examples/H2_example.jpg"], ["examples/H3_example.jpg"], ["examples/H5_example.jpg"], ["examples/H6_example.jpg"], ], allow_flagging="never" ).launch()