""" 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"""
{info['zh']}
{top_class}
{confidence:.1%}
{badge_text}
投放建議
{info['tip']} {"

置信度偏低,建議人工核對後再投放。" if confidence < 0.5 else ""}
""" return label_probs, card def _empty_card(): return """
上傳圖片後識別結果將顯示於此
""" def build_ui(model, device): with gr.Blocks(title="垃圾智能識別", css=CSS) as demo: gr.HTML(""" """) 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('
') gr.HTML("""
類別中文常見物品投放方式
biodegradable可生物降解食物殘渣、果皮廚餘回收桶
cardboard紙板快遞箱、飲料盒紙類回收箱(壓平)
glass玻璃玻璃瓶、玻璃杯玻璃回收桶
metal金屬鋁罐、鐵罐金屬回收桶(沖洗)
paper紙類報紙、紙袋紙類回收箱(乾燥)
plastic塑料塑料瓶、包裝袋塑料回收桶(沖洗)
""") gr.HTML('
本系統僅供輔助參考,結果不保證完全準確,低置信度時請人工判斷。
') 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()