Spaces:
Sleeping
Sleeping
import torch | |
from torchvision import transforms | |
from PIL import Image | |
import gradio as gr | |
import json | |
# Charger les noms des classes | |
with open("class_names.json", "r") as f: | |
class_names = json.load(f) | |
# Charger le modèle | |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
model = torch.load("efficientnet_b7_best.pth", map_location=device) | |
model.eval() # Mode évaluation | |
# Définir la taille de l'image | |
image_size = (224, 224) | |
# Transformation pour l'image | |
class GrayscaleToRGB: | |
def __call__(self, img): | |
return img.convert("RGB") | |
valid_test_transforms = transforms.Compose([ | |
transforms.Grayscale(num_output_channels=1), | |
transforms.Resize(image_size), | |
GrayscaleToRGB(), # Conversion en RGB | |
transforms.ToTensor(), | |
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) | |
]) | |
# Fonction de prédiction | |
def predict_image(image): | |
image_tensor = valid_test_transforms(image).unsqueeze(0).to(device) | |
with torch.no_grad(): | |
outputs = model(image_tensor) | |
_, predicted_class = torch.max(outputs, 1) | |
predicted_label = class_names[predicted_class.item()] | |
return predicted_label | |
# Interface Gradio | |
interface = gr.Interface( | |
fn=predict_image, | |
inputs=gr.Image(type="pil"), | |
outputs="text", | |
title="Prédiction d'images avec PyTorch", | |
description="Chargez une image pour obtenir une prédiction de classe." | |
) | |
if __name__ == "__main__": | |
interface.launch() | |