Spaces:
Sleeping
Sleeping
File size: 9,052 Bytes
871ff08 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | """
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"""
<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()
|