Download app_dict.py from Cheomjee/0801eff: direct link, hf CLI and curl.
- Browser
- Download file 1.79 kB
-
https://huggingface.co/spaces/Cheomjee/0801eff/resolve/main/app_dict.py
- Command line
-
hf download hf://spaces/Cheomjee/0801eff/app_dict.py
-
curl -L -o app_dict.py https://huggingface.co/spaces/Cheomjee/0801eff/resolve/main/app_dict.py
1.79 kB
| import torch | |
| import torchvision.transforms as transforms | |
| from torchvision import models | |
| from PIL import Image | |
| import gradio as gr | |
| # ๋ชจ๋ธ ํด๋์ค ์ ์ (ResNet18) | |
| class MyModel(torch.nn.Module): | |
| def __init__(self, num_classes): | |
| super(MyModel, self).__init__() | |
| self.model = models.resnet18(weights=None) # ResNet18 ๋ชจ๋ธ ์ฌ์ฉ | |
| self.model.fc = torch.nn.Linear(self.model.fc.in_features, num_classes) # ๋ง์ง๋ง ๋ ์ด์ด ์์ | |
| def forward(self, x): | |
| return self.model(x) | |
| # ๋ชจ๋ธ ์ด๊ธฐํ | |
| num_classes = 6 # ํด๋์ค ์์ ๋ง๊ฒ ์ค์ | |
| model = MyModel(num_classes) | |
| # ๋ชจ๋ธ ๊ฐ์ค์น ๋ก๋ (CPU๋ก ๋งคํ) | |
| model.load_state_dict(torch.load('resnet18_finetuned_2.pth', map_location=torch.device('cpu')), strict=False) | |
| model.eval() | |
| # ๋ฐ์ดํฐ ๋ณํ ์ ์ | |
| transform = transforms.Compose([ | |
| transforms.Resize((224, 224)), | |
| transforms.ToTensor(), | |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) | |
| ]) | |
| # ํด๋์ค ์ด๋ฆ ๋ฆฌ์คํธ ์ ์ | |
| class_names = ['disposablecup', 'envmark', 'label', 'mug', 'nonlabel', 'reusablecup'] | |
| def predict(image): | |
| image = transform(image).unsqueeze(0) | |
| with torch.no_grad(): | |
| outputs = model(image) | |
| print("Raw outputs:", outputs) # ์๋ณธ ์ถ๋ ฅ๊ฐ ํ์ธ | |
| _, predicted = torch.max(outputs, 1) | |
| label = class_names[predicted.item()] | |
| if label in ['disposablecup','label'] : result = "Failed" | |
| else : result = "Successed (+1)" | |
| # ์์ธก ๊ฒฐ๊ณผ์ ์๋ณธ ์ถ๋ ฅ๊ฐ์ ๋ชจ๋ ๋ฐํ | |
| return result # ์๋ณธ ์ถ๋ ฅ๊ฐ์ NumPy ๋ฐฐ์ด๋ก ๋ณํํ์ฌ ๋ฐํ | |
| # Gradio ์ธํฐํ์ด์ค ์ค์ (๋ ๊ฐ์ ์ถ๋ ฅ) | |
| iface = gr.Interface(fn=predict, inputs=gr.Image(type='pil'), outputs=['label', 'numpy'], live=True) | |
| iface.launch() | |