Spaces:
Runtime error
Runtime error
Commit
·
efb2a0e
1
Parent(s):
986506c
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,57 @@
|
|
| 1 |
import streamlit as st
|
|
|
|
|
|
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
from io import StringIO
|
| 3 |
+
import requests
|
| 4 |
|
| 5 |
+
import torch
|
| 6 |
+
from torchvision.models.inception import inception_v3
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
from skimage.transform import resize
|
| 9 |
|
| 10 |
+
@st.cache
|
| 11 |
+
def load_stuff():
|
| 12 |
+
model = inception_v3(pretrained=True, # load existing weights
|
| 13 |
+
transform_input=True, # preprocess input image the same way as in training
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
model.aux_logits = False # don't predict intermediate logits (yellow layers at the bottom)
|
| 17 |
+
model.train(False)
|
| 18 |
+
|
| 19 |
+
LABELS_URL = 'https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json'
|
| 20 |
+
labels = {i: c for i, c in enumerate(requests.get(LABELS_URL).json())}
|
| 21 |
+
return model, labels
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
model, labels = load_stuff()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def transform_input(img):
|
| 28 |
+
return torch.as_tensor(img.reshape([1, 299, 299, 3]).transpose([0, 3, 1, 2]), dtype=torch.float32)
|
| 29 |
|
| 30 |
|
| 31 |
+
def predict(img):
|
| 32 |
+
img = transform_input(img)
|
| 33 |
+
probs = torch.nn.functional.softmax(model(img), dim=-1)
|
| 34 |
+
probs = probs.data.numpy()
|
| 35 |
+
top_ix = probs.ravel().argsort()[-1:-10:-1]
|
| 36 |
+
s = 'top-10 classes are: \n\n [prob : class label]\n\n'
|
| 37 |
+
for l in top_ix:
|
| 38 |
+
s = s + '%.4f :\t%s' % (probs.ravel()[l], labels[l].split(',')[0]) + '\n\n'
|
| 39 |
+
return s
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
st.markdown("### Hello dude!")
|
| 44 |
+
|
| 45 |
+
uploaded_file = st.file_uploader("Choose a file")
|
| 46 |
+
if uploaded_file is not None:
|
| 47 |
+
# To read file as bytes:
|
| 48 |
+
bytes_data = uploaded_file.getvalue()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
with open('tmp', 'wb')as f:
|
| 52 |
+
f.write(bytes_data)
|
| 53 |
+
img = resize(plt.imread('tmp'), (299, 299))[..., :3]
|
| 54 |
+
|
| 55 |
+
top_classes = predict(img)
|
| 56 |
+
st.markdown(top_classes)
|
| 57 |
+
st.image('tmp')
|