File size: 2,343 Bytes
466dfb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
import torch
import torch.nn as nn
from PIL import Image
from torchvision import transforms
import torchvision
import gradio as gr

weights = torchvision.models.GoogLeNet_Weights.DEFAULT
transfer_model_transformer = weights.transforms()

transfer_model = torchvision.models.googlenet(weights=weights)
transfer_model.classifier = nn.Sequential(
    nn.Dropout(p=0.2), nn.Linear(in_features=1024, out_features=512), nn.ReLU(),
    nn.Linear(in_features=512, out_features=256), nn.ReLU(),
    nn.Linear(in_features=256, out_features=128), nn.ReLU(),
    nn.Linear(in_features=128, out_features=64), nn.ReLU(),
    nn.Linear(in_features=64, out_features=32), nn.ReLU(),
    nn.Linear(in_features=32, out_features=16), nn.ReLU(),
    nn.Linear(in_features=16, out_features=8), nn.ReLU(),
    nn.Linear(in_features=8, out_features=4), nn.ReLU(),
    nn.Linear(in_features=4, out_features=2)
)

# Modeli CPU üzerinde yükle
transfer_model.load_state_dict(torch.load("best_model_transfer.pth", map_location=torch.device('cpu')))

class_names = ['Tere', 'Roka']

def predict(img):
    """Transforms and performs a prediction on img and returns prediction and time taken."""
    # Transform the target image and add a batch dimension
    img = transfer_model_transformer(img).unsqueeze(0)

    # Put model into evaluation mode and turn on inference mode
    transfer_model.eval()
    transfer_model.to("cpu")
    with torch.inference_mode():
        # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
        pred_probs = torch.softmax(transfer_model(img), dim=1)

    # Create a prediction label and prediction probability dictionary for each prediction class
    pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}

    return pred_labels_and_probs

# Create title, description and article strings
title = "CRESS ARUGULA DISTINCTIVE"
description = "An artificial intelligence application that recognizes whether the photo uploaded to the system is cress or arugula."

# Create the Gradio demo
demo = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil"),
    outputs=[gr.Label(num_top_classes=len(class_names), label="Predictions")],
    title=title,
    description=description
)

# Launch the demo!
demo.launch(debug=False, share=True)