Spaces:
Sleeping
Sleeping
Download app.py from Kazuyakaz/Sports_Classifier: direct link, hf CLI and curl.
- Browser
- Download file 2.24 kB
-
https://huggingface.co/spaces/Kazuyakaz/Sports_Classifier/resolve/main/app.py
- Command line
-
hf download hf://spaces/Kazuyakaz/Sports_Classifier/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Kazuyakaz/Sports_Classifier/resolve/main/app.py
2.24 kB
| 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() | |