File size: 1,372 Bytes
c46c672
07952a9
 
22a9bc1
 
07952a9
 
 
 
c46c672
3edf187
07952a9
 
 
 
 
 
159dc7c
 
 
07952a9
159dc7c
f05318e
159dc7c
 
 
 
 
 
 
3edf187
22a9bc1
e36a241
159dc7c
3edf187
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
import gradio as gr
from transformers import AutoModelForImageClassification, AutoFeatureExtractor
import torch
from PIL import Image

# Load the model and feature extractor once during initialization
model_name = "amjadfqs/finalProject"
model = AutoModelForImageClassification.from_pretrained(model_name)
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)

def predict(image):
    # Preprocess the image
    inputs = feature_extractor(images=image, return_tensors="pt")
    # Make prediction
    with torch.no_grad():
        outputs = model(**inputs)
    logits = outputs.logits
    # Calculate the confidence values
    softmax = torch.nn.functional.softmax(logits, dim=1)
    confidences = softmax.squeeze().tolist()
    # Get the predicted class
    predicted_class_index = logits.argmax(-1).item()
    class_names = ["glioma", "meningioma", "notumor", "pituitary"]
    predicted_class = class_names[predicted_class_index]
    # Create a dictionary to return both the predicted class and the confidence values
    result = {
        "predicted_class": predicted_class,
        "confidences": {class_names[i]: confidences[i] for i in range(len(class_names))}
    }
    return result

# Set up the Gradio interface
image_cp = gr.Image(type="pil", label='Brain')
interface = gr.Interface(fn=predict, inputs=image_cp, outputs="json")
interface.launch()