""" Gradio web demo for garbage classification. Usage: python src/app.py --model resnet50 python src/app.py --model resnet50 --share """ import argparse from pathlib import Path import gradio as gr import torch from PIL import Image from torchvision import transforms from dataset import CLASSES from model import MODEL_REGISTRY BASE_DIR = Path(__file__).parent IMG_SIZE = 224 CLASS_INFO = { "biodegradable": {"zh": "可生物降解", "tip": "請投入廚餘或有機回收桶,可用於堆肥。"}, "cardboard": {"zh": "紙板", "tip": "壓平後投入紙類回收箱。"}, "glass": {"zh": "玻璃", "tip": "小心投入玻璃回收桶,避免破碎。"}, "metal": {"zh": "金屬", "tip": "沖洗後投入金屬回收桶。"}, "paper": {"zh": "紙類", "tip": "保持乾燥,投入紙類回收箱。"}, "plastic": {"zh": "塑料", "tip": "沖洗後投入塑料回收桶。"}, } TRANSFORM = transforms.Compose([ transforms.Resize((IMG_SIZE, IMG_SIZE)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), ]) CSS = """ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap'); * { font-family: 'Inter', sans-serif !important; } body { background: #fafafa !important; } .gradio-container { max-width: 880px !important; margin: 0 auto !important; padding: 32px 24px !important; } /* 隱藏 Gradio 預設頁腳 */ footer { display: none !important; } /* 頁面標題區 */ #page-header { margin-bottom: 32px; padding-bottom: 24px; border-bottom: 1px solid #e5e5e5; } #page-header h1 { font-size: 1.6rem; font-weight: 600; color: #111; margin: 0 0 6px 0; letter-spacing: -0.3px; } #page-header p { font-size: 0.875rem; color: #888; margin: 0; } /* 標籤文字 */ label.svelte-1b6s6s, .block > label { font-size: 0.8rem !important; font-weight: 500 !important; color: #555 !important; text-transform: uppercase !important; letter-spacing: 0.5px !important; } /* 上傳區域 */ .upload-wrap { border: 1.5px solid #e0e0e0 !important; border-radius: 12px !important; background: #fff !important; transition: border-color 0.2s; } .upload-wrap:hover { border-color: #bbb !important; } /* 識別按鈕 */ #predict-btn button, #predict-btn { background: #111 !important; color: #fff !important; border: none !important; border-radius: 8px !important; font-size: 0.875rem !important; font-weight: 500 !important; height: 44px !important; letter-spacing: 0.2px !important; transition: background 0.15s !important; } #predict-btn button:hover, #predict-btn:hover { background: #333 !important; } /* 結果卡片 */ #result-card { background: #fff; border: 1.5px solid #e0e0e0; border-radius: 12px; padding: 24px; min-height: 120px; } /* 概率圖 */ .label-wrap { border-radius: 10px !important; } /* 分割線 */ .divider { border: none; border-top: 1px solid #ebebeb; margin: 28px 0; } /* 說明表格 */ #info-table { width: 100%; border-collapse: collapse; font-size: 0.875rem; color: #444; } #info-table th { text-align: left; padding: 8px 12px; font-weight: 500; color: #888; font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.4px; border-bottom: 1px solid #ebebeb; } #info-table td { padding: 10px 12px; border-bottom: 1px solid #f3f3f3; } #info-table tr:last-child td { border-bottom: none; } /* 底部說明 */ #disclaimer { font-size: 0.78rem; color: #bbb; text-align: center; margin-top: 32px; } """ def load_model(model_name: str, device): model = MODEL_REGISTRY[model_name]() ckpt = BASE_DIR / f"best_{model_name}.pth" if not ckpt.exists(): raise FileNotFoundError(f"找不到模型權重:{ckpt}") model.load_state_dict(torch.load(ckpt, map_location=device)) model.eval() return model.to(device) def predict(model, device, image: Image.Image): if image is None: return {}, _empty_card() tensor = TRANSFORM(image.convert("RGB")).unsqueeze(0).to(device) with torch.no_grad(): probs = torch.softmax(model(tensor), dim=1)[0].cpu().tolist() top_idx = int(torch.tensor(probs).argmax()) top_class = CLASSES[top_idx] confidence = probs[top_idx] info = CLASS_INFO[top_class] label_probs = { f"{CLASSES[i]} ({CLASS_INFO[CLASSES[i]]['zh']})": round(probs[i], 4) for i in range(len(CLASSES)) } if confidence >= 0.85: badge_bg, badge_fg, badge_text = "#d1fae5", "#065f46", "高置信度" elif confidence >= 0.5: badge_bg, badge_fg, badge_text = "#fef3c7", "#92400e", "中置信度" else: badge_bg, badge_fg, badge_text = "#fee2e2", "#991b1b", "低置信度" card = f"""
基於 ResNet50 遷移學習 · 測試準確率 96.11% · 6 類別
| 類別 | 中文 | 常見物品 | 投放方式 |
|---|---|---|---|
| biodegradable | 可生物降解 | 食物殘渣、果皮 | 廚餘回收桶 |
| cardboard | 紙板 | 快遞箱、飲料盒 | 紙類回收箱(壓平) |
| glass | 玻璃 | 玻璃瓶、玻璃杯 | 玻璃回收桶 |
| metal | 金屬 | 鋁罐、鐵罐 | 金屬回收桶(沖洗) |
| paper | 紙類 | 報紙、紙袋 | 紙類回收箱(乾燥) |
| plastic | 塑料 | 塑料瓶、包裝袋 | 塑料回收桶(沖洗) |