Spaces:
Sleeping
Sleeping
File size: 2,244 Bytes
a01f19c ff7a1fa a01f19c 2ff67d1 a01f19c 34e399e a01f19c 12689c6 a01f19c 94973a7 a01f19c 75e5e0b a01f19c | 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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | import gradio as gr
import torch
import json
import numpy as np
from PIL import Image
import albumentations as A
from albumentations.pytorch import ToTensorV2
from model import create_sports_model
from timeit import default_timer as timer
from typing import Tuple, Dict
import os
# クラス名読み込み
with open("class_names.json", "r") as f:
class_names = json.load(f)
# 推論用transform
inference_transform = A.Compose([
A.Resize(288, 288),
A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
ToTensorV2()
])
# モデル読み込み
model = create_sports_model(class_names=len(class_names))
# 保存されたチェックポイントを読み込み
checkpoint = torch.load("2025-06-30_23-46-38_EfficientNet_epoch7_vallloss0.0733.pth", map_location=torch.device("cpu"))
# チェックポイントの構造を確認して適切に読み込み
if 'model_dict' in checkpoint:
model.load_state_dict(checkpoint['model_dict'])
elif 'state_dict' in checkpoint:
model.load_state_dict(checkpoint['state_dict'])
else:
model.load_state_dict(checkpoint)
model.eval()
def predict(image) -> Tuple[Dict, float]:
start_time = timer()
image = np.array(image)
transformed = inference_transform(image=image)
image_tensor = transformed['image'].unsqueeze(0)
# 推論
with torch.no_grad():
outputs = model(image_tensor)
probabilities = torch.softmax(outputs, dim=1)
# 結果を辞書形式に変換
pred_dict = {class_names[i]: float(probabilities[0][i]) for i in range(len(class_names))}
pred_time = round(timer() - start_time, 4)
return pred_dict, pred_time
# Gradio インターフェース
title = " Sport Classifier "
description = "An EfficientNetV2 model to classify 100 different types of Sports. Upload an image to see the prediction!"
article = "Built with PyTorch and timm, deployed on Hugging Face Spaces."
demo = gr.Interface(
fn=predict,
inputs=gr.Image(type='pil'),
outputs=[
gr.Label(num_top_classes=10, label="Predictions"),
gr.Number(label="Predicion time (s)")
],
title=title,
description=description,
article=article
)
if __name__=="__main__":
demo.launch()
|