Spaces:
Sleeping
Sleeping
Add garbage classifier app with ResNet50 model
Browse filesFiles changed (5)
- app.pyAdded+296
- best_resnet50.pthAdded+3
- dataset.pyAdded+81
- model.pyAdded+68
- requirements.txtAdded+5
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296"""Gradio web demo for garbage classification.
Usage: python src/app.py --model resnet50 python src/app.py --model resnet50 --share"""
import argparsefrom pathlib import Path
import gradio as grimport torchfrom PIL import Imagefrom torchvision import transforms
from dataset import CLASSESfrom model import MODEL_REGISTRY
BASE_DIR = Path(__file__).parentIMG_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""" <div id="result-card"> <div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:18px"> <div> <div style="font-size:1.4rem; font-weight:600; color:#111; letter-spacing:-0.3px"> {info['zh']} </div> <div style="font-size:0.85rem; color:#888; margin-top:3px">{top_class}</div> </div> <div style="text-align:right"> <div style="font-size:1.6rem; font-weight:700; color:#111">{confidence:.1%}</div> <span style="background:{badge_bg}; color:{badge_fg}; font-size:0.75rem; padding:2px 9px; border-radius:6px; font-weight:500"> {badge_text} </span> </div> </div> <div style="background:#f7f7f7; border-radius:8px; padding:12px 16px; font-size:0.875rem; color:#555; line-height:1.6"> <span style="font-weight:500; color:#333">投放建議</span><br> {info['tip']} {"<br><br><span style='color:#999'>置信度偏低,建議人工核對後再投放。</span>" if confidence < 0.5 else ""} </div> </div> """ return label_probs, card
def _empty_card(): return """ <div id="result-card" style="display:flex; align-items:center; justify-content:center; color:#ccc"> <span style="font-size:0.9rem">上傳圖片後識別結果將顯示於此</span> </div> """
def build_ui(model, device): with gr.Blocks(title="垃圾智能識別", css=CSS) as demo:
gr.HTML(""" <div id="page-header"> <h1>垃圾智能識別</h1> <p>基於 ResNet50 遷移學習 · 測試準確率 96.11% · 6 類別</p> </div> """)
with gr.Row(equal_height=False): with gr.Column(scale=1): img_input = gr.Image( type="pil", label="上傳圖片", elem_classes=["upload-wrap"], height=280, ) btn = gr.Button("識別", elem_id="predict-btn")
with gr.Column(scale=1): result_html = gr.HTML(_empty_card()) prob_chart = gr.Label(num_top_classes=6, label="各類別概率")
gr.HTML('<hr class="divider">')
gr.HTML(""" <table id="info-table"> <thead> <tr><th>類別</th><th>中文</th><th>常見物品</th><th>投放方式</th></tr> </thead> <tbody> <tr><td>biodegradable</td><td>可生物降解</td><td>食物殘渣、果皮</td><td>廚餘回收桶</td></tr> <tr><td>cardboard</td><td>紙板</td><td>快遞箱、飲料盒</td><td>紙類回收箱(壓平)</td></tr> <tr><td>glass</td><td>玻璃</td><td>玻璃瓶、玻璃杯</td><td>玻璃回收桶</td></tr> <tr><td>metal</td><td>金屬</td><td>鋁罐、鐵罐</td><td>金屬回收桶(沖洗)</td></tr> <tr><td>paper</td><td>紙類</td><td>報紙、紙袋</td><td>紙類回收箱(乾燥)</td></tr> <tr><td>plastic</td><td>塑料</td><td>塑料瓶、包裝袋</td><td>塑料回收桶(沖洗)</td></tr> </tbody> </table> """)
gr.HTML('<div id="disclaimer">本系統僅供輔助參考,結果不保證完全準確,低置信度時請人工判斷。</div>')
btn.click( fn=lambda img: predict(model, device, img), inputs=img_input, outputs=[prob_chart, result_html], ) img_input.change( fn=lambda img: predict(model, device, img), inputs=img_input, outputs=[prob_chart, result_html], )
return demo
def main(): device = torch.device("cpu") print("載入模型 resnet50...") model = load_model("resnet50", device) demo = build_ui(model, device) demo.launch()
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:ae05354a59a8610fac5fd5ce07312fbac0de9542756b12e9f74a2b4cdac325f5size 94401315123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Dataset loader for garbage classification.Supports both COCO JSON format and pre-split JSON format (from split_dataset.py)."""
import jsonimport osfrom collections import defaultdictfrom pathlib import Path
import torchfrom PIL import Imagefrom torch.utils.data import Dataset, WeightedRandomSampler
CLASSES = ["biodegradable", "cardboard", "glass", "metal", "paper", "plastic"]CLASS_TO_IDX = {c: i for i, c in enumerate(CLASSES)}
class GarbageDataset(Dataset): def __init__(self, json_path: str, img_dir: str = None, transform=None): """ Accepts two formats: 1. COCO JSON + img_dir (original format) 2. Pre-split JSON from split_dataset.py (list of {path, label}) """ with open(json_path) as f: data = json.load(f)
if isinstance(data, list): # Pre-split format: [{path, label}, ...] self.samples = [(d["path"], d["label"]) for d in data if os.path.exists(d["path"])] else: # COCO format self.samples = self._load_coco(data, img_dir)
self.transform = transform
def _load_coco(self, coco, img_dir): cat_map = {c["id"]: c["name"] for c in coco["categories"]} img_file = {img["id"]: img["file_name"] for img in coco["images"]}
img_cat_area = defaultdict(lambda: defaultdict(float)) for ann in coco["annotations"]: img_cat_area[ann["image_id"]][ann["category_id"]] += ann["area"]
samples = [] for img_id, cat_areas in img_cat_area.items(): dominant = max(cat_areas, key=cat_areas.get) name = cat_map[dominant] if name not in CLASS_TO_IDX: continue fpath = os.path.join(img_dir, img_file[img_id]) if os.path.exists(fpath): samples.append((fpath, CLASS_TO_IDX[name])) return samples
def __len__(self): return len(self.samples)
def __getitem__(self, idx): fpath, label = self.samples[idx] img = Image.open(fpath).convert("RGB") if self.transform: img = self.transform(img) return img, label
def class_counts(self): counts = [0] * len(CLASSES) for _, label in self.samples: counts[label] += 1 return counts
def make_weighted_sampler(dataset: GarbageDataset) -> WeightedRandomSampler: counts = dataset.class_counts() total = sum(counts) weights_per_class = [total / (c + 1e-6) for c in counts] sample_weights = [weights_per_class[label] for _, label in dataset.samples] return WeightedRandomSampler(sample_weights, num_samples=len(sample_weights), replacement=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Transfer learning models for garbage classification.Supports MobileNetV3-Small, EfficientNet-B0, ResNet50."""
import torchimport torch.nn as nnfrom torchvision import models
NUM_CLASSES = 6
def build_mobilenetv3(freeze_backbone: bool = False) -> nn.Module: """MobileNetV3-Small with custom classification head.""" model = models.mobilenet_v3_small(weights=models.MobileNet_V3_Small_Weights.IMAGENET1K_V1) if freeze_backbone: for param in model.features.parameters(): param.requires_grad = False in_features = model.classifier[3].in_features model.classifier[3] = nn.Linear(in_features, NUM_CLASSES) return model
def build_efficientnet_b0(freeze_backbone: bool = False) -> nn.Module: """EfficientNet-B0 with custom classification head.""" model = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.IMAGENET1K_V1) if freeze_backbone: for param in model.features.parameters(): param.requires_grad = False in_features = model.classifier[1].in_features model.classifier[1] = nn.Linear(in_features, NUM_CLASSES) return model
def build_simple_cnn() -> nn.Module: """Baseline 5-layer CNN (scratch) for comparison.""" return nn.Sequential( nn.Conv2d(3, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(128, 256, 3, padding=1), nn.BatchNorm2d(256), nn.ReLU(), nn.AdaptiveAvgPool2d(4), nn.Flatten(), nn.Linear(256 * 4 * 4, 512), nn.ReLU(), nn.Dropout(0.4), nn.Linear(512, NUM_CLASSES), )
def build_resnet50(freeze_backbone: bool = False) -> nn.Module: """ResNet50 with custom classification head.""" model = models.resnet50(weights=models.ResNet50_Weights.IMAGENET1K_V2) if freeze_backbone: for name, param in model.named_parameters(): if "layer4" not in name and "fc" not in name: param.requires_grad = False model.fc = nn.Sequential( nn.Dropout(0.3), nn.Linear(model.fc.in_features, NUM_CLASSES) ) return model
MODEL_REGISTRY = { "mobilenetv3": build_mobilenetv3, "efficientnet_b0": build_efficientnet_b0, "resnet50": build_resnet50, "simple_cnn": build_simple_cnn,}12345torch==2.7.0torchvision==0.22.0Pillowgradionumpyapp.pyAdded+296
best_resnet50.pthAdded+3
dataset.pyAdded+81
model.pyAdded+68
requirements.txtAdded+5