Spaces:
Build error
Build error
Add application file
Browse files- app.py +50 -0
- requirements.txt +3 -0
app.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from torchvision import transforms
|
| 4 |
+
from torchvision.models import ResNet34_Weights, resnet34
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def image_classifier(image):
|
| 8 |
+
# Готовим данные
|
| 9 |
+
inputs = transform(image)
|
| 10 |
+
inputs = inputs.unsqueeze(0)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# Пропускаем данные через модель
|
| 14 |
+
with torch.no_grad():
|
| 15 |
+
outputs = model(inputs)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Ставим метки и вероятности
|
| 19 |
+
predictions = torch.nn.functional.softmax(outputs[0], dim=0)
|
| 20 |
+
# TODO: оставить в predictions только 5 самых вероятных вариантов
|
| 21 |
+
top_prediction_1, top_prediction_2 = torch.topk(predictions, 5)
|
| 22 |
+
return {labels[p]: float(top_prediction_1[i]) for i, p in enumerate(top_prediction_2)}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# Заранее обученная модель
|
| 26 |
+
model = resnet34(weights=ResNet34_Weights.DEFAULT)
|
| 27 |
+
model.to('cpu')
|
| 28 |
+
model.eval()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Преобразования над сырыми данными
|
| 32 |
+
transform = transforms.Compose([
|
| 33 |
+
transforms.Resize(256),
|
| 34 |
+
transforms.CenterCrop(224),
|
| 35 |
+
transforms.ToTensor(),
|
| 36 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
| 37 |
+
std=[0.229, 0.224, 0.225]),
|
| 38 |
+
])
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# Названия классов
|
| 42 |
+
labels = ResNet34_Weights.DEFAULT.meta["categories"]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
img_widget = gr.Image(image_mode='RGB', type='pil')
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# TODO: добавить код приложения Gradio
|
| 49 |
+
demo = gr.Interface(fn=image_classifier, inputs=gr.Image, outputs=gr.Label(num_top_classes=5))
|
| 50 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
torch
|
| 3 |
+
torchvision
|