hmmrg commited on
Commit
f572cda
·
verified ·
1 Parent(s): f5985fd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -48
app.py CHANGED
@@ -1,55 +1,19 @@
1
- import torch
2
- from PIL import Image
3
- import torchvision.models as models
4
- from torchvision import transforms
5
  import gradio as gr
 
 
6
 
7
- # Load the PyTorch model
8
- #model = torch.load("model.pth") # Replace with the path to your trained model
9
- model = models.resnet18(pretrained=False) # Instantiate ResNet18 without pre-trained weights
10
- # Load the saved weights
11
- model.load_state_dict(torch.load("model.pth"))
12
- model.eval() # Set the model to evaluation mode
13
 
14
- # Define preprocessing transformations
15
- preprocess = transforms.Compose([
16
- transforms.Resize((224, 224)), # Resize image to match model's expected input size
17
- transforms.ToTensor(), # Convert image to tensor
18
- transforms.Normalize( # Normalize with ImageNet mean and std
19
- mean=[0.485, 0.456, 0.406],
20
- std=[0.229, 0.224, 0.225]
21
- )
22
- ])
23
 
24
- # Define the class labels
25
- class_labels = ["Sailboat", "Fish"] # Update these labels based on your dataset
26
 
27
- # Define the prediction function
28
- def predict(image):
29
- # Preprocess the input image
30
- input_tensor = preprocess(image).unsqueeze(0) # Add batch dimension
31
 
32
- # Perform inference
33
- with torch.no_grad():
34
- output = model(input_tensor)
35
- probabilities = torch.nn.functional.softmax(output[0], dim=0)
 
36
 
37
- # Get the predicted class index as an int
38
- predicted_index = int(torch.argmax(probabilities).item())
39
-
40
- confidence = probabilities[predicted_index].item()
41
-
42
- return {class_labels[predicted_index]: confidence}
43
-
44
- # Create the Gradio interface
45
- interface = gr.Interface(
46
- fn=predict, # Prediction function
47
- inputs=gr.Image(type="pil"), # Input is an image (handled as a PIL.Image)
48
- outputs=gr.Label(num_top_classes=2), # Output is a label with top 2 class probabilities
49
- title="Sailboat or Fish Classifier",
50
- description="Upload an image to classify it as either a sailboat or a fish.",
51
- )
52
-
53
- # Launch the app
54
- if __name__ == "__main__":
55
- interface.launch()
 
 
 
 
 
1
  import gradio as gr
2
+ from fastai.learner import load_learner
3
+ from fastai.vision.core import PILImage
4
 
 
 
 
 
 
 
5
 
6
+ from huggingface_hub import hf_hub_download
 
 
 
 
 
 
 
 
7
 
 
 
8
 
9
+ learner = load_learner(hf_hub_download("hmmrg/itisasailboat2","model.pkl"))
 
 
 
10
 
11
+ def classify_image(image):
12
+ img = PILImage.create(image)
13
+ pred_class, pred_idx, outputs = learner.predict(img)
14
+ return(f"Predicted class: {pred_class}")
15
+
16
 
17
+ gr.Interface(fn=classify_image,
18
+ inputs=gr.Image(width=224, height=224),
19
+ outputs="textbox").launch()