File size: 1,516 Bytes
347cd1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()