Spaces:
Sleeping
Sleeping
Added application files
Browse files- .gitignore +2 -0
- README.md +1 -1
- app.py +19 -0
- examples/cat_image.jpg +0 -0
- examples/dog_image.jpeg +0 -0
- model.pt +3 -0
- utils.py +24 -0
.gitignore
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
__pycache__/
|
2 |
+
*.py[cod]
|
README.md
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
---
|
2 |
-
title: Test-
|
3 |
emoji: π
|
4 |
colorFrom: blue
|
5 |
colorTo: red
|
|
|
1 |
---
|
2 |
+
title: Test - Cat or Dog
|
3 |
emoji: π
|
4 |
colorFrom: blue
|
5 |
colorTo: red
|
app.py
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from utils import process_image, load_saved_model
|
3 |
+
import gradio as gr
|
4 |
+
|
5 |
+
MODEL_PATH = "model.pt"
|
6 |
+
CATEGORIES = ("Dog", "Cat")
|
7 |
+
model = load_saved_model(MODEL_PATH)
|
8 |
+
|
9 |
+
def predict_pet(image):
|
10 |
+
with torch.no_grad():
|
11 |
+
model.eval()
|
12 |
+
x = process_image(image)
|
13 |
+
probs = model(x).squeeze().tolist()
|
14 |
+
|
15 |
+
return dict(zip(CATEGORIES, probs))
|
16 |
+
|
17 |
+
demo = gr.Interface(fn=predict_pet, inputs=gr.Image(label="Image"), outputs=gr.Label(label="Type of Pet"), allow_flagging="never",
|
18 |
+
title="Cat or Dog ?", examples="examples", description="This is a small image classification model for cats and dogs")
|
19 |
+
demo.launch()
|
examples/cat_image.jpg
ADDED
examples/dog_image.jpeg
ADDED
model.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4e64468ae993ab21d24e47258f71f3333fd73145de5d7e8bfa1908bec33e1215
|
3 |
+
size 103037468
|
utils.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torchvision.transforms as T
|
5 |
+
|
6 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
7 |
+
transforms = T.Compose([T.ToPILImage(), T.Resize(size=224), T.ToTensor()])
|
8 |
+
|
9 |
+
def load_saved_model(path: str, device:torch.device = DEVICE) -> nn.Module:
|
10 |
+
"""
|
11 |
+
Load the PyTorch model
|
12 |
+
"""
|
13 |
+
loaded_trace = torch.jit.load(path, map_location=device)
|
14 |
+
model = nn.Sequential(loaded_trace, nn.Softmax(dim=1))
|
15 |
+
return model
|
16 |
+
|
17 |
+
def process_image(x: np.ndarray, device:torch.device = DEVICE) -> torch.Tensor:
|
18 |
+
"""
|
19 |
+
Takes a numpy array provided by gradio as input and returns a ready to be used tensor with the same processing use for training.
|
20 |
+
"""
|
21 |
+
x = transforms(x)
|
22 |
+
x = x.unsqueeze(0)
|
23 |
+
x = x.to(device)
|
24 |
+
return x
|