Spaces:
Sleeping
Sleeping
FEAT: Add Jinja2 demo page
Browse files新增 /demo 路由與 Jinja2 前端頁面,可上傳圖片並顯示模型預測結果。\n保留既有 /predict JSON API,並將 jinja2 加入直接依賴。
Files changed (4)
- app.py+81-14
- pyproject.toml+1
- templates/demo.htmlAdded+205
- uv.lock+2
123456789101110 unmodified lines222324252627282930313233343536373839404142439 unmodified lines53545556from contextlib import asynccontextmanagerfrom io import BytesIOfrom fastapi import FastAPI, File, HTTPException, UploadFilefrom PIL import Image, UnidentifiedImageErrorfrom model_service import MODEL_PATH, get_model_service@asynccontextmanagerasync def lifespan(_: FastAPI):10 unmodified lines)@app.get("/")def root():return {"message": "Presence Detection API","docs": "/docs","model_path": str(MODEL_PATH.name),}@app.get("/health")def health():return {"status": "ok", "model_loaded": True}@app.post("/predict")async def predict(file: UploadFile = File(...)):if not file.content_type or not file.content_type.startswith("image/"):raise HTTPException(status_code=400, detail="Uploaded file must be an image.")9 unmodified linesresult = get_model_service().predict_image(image)result["filename"] = file.filenameresult["content_type"] = file.content_typereturn result12345678910111213141516171810 unmodified lines2930313233343536373839404142434445464748499 unmodified lines5960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123import base64from contextlib import asynccontextmanagerfrom io import BytesIOfrom pathlib import Pathfrom fastapi import FastAPI, File, HTTPException, Request, UploadFilefrom fastapi.responses import HTMLResponsefrom fastapi.templating import Jinja2Templatesfrom PIL import Image, UnidentifiedImageErrorfrom model_service import MODEL_PATH, get_model_serviceBASE_DIR = Path(__file__).resolve().parenttemplates = Jinja2Templates(directory=str(BASE_DIR / "templates"))@asynccontextmanagerasync def lifespan(_: FastAPI):10 unmodified lines)def _build_demo_context(**overrides):context = {"image_data_url": None,"result_label": "Normal","result_label_zh": "正常","class_label": "-","confidence": "-","acc": "-","error": None,}context.update(overrides)return contextasync def _predict_upload(file: UploadFile) -> tuple[dict, bytes]:if not file.content_type or not file.content_type.startswith("image/"):raise HTTPException(status_code=400, detail="Uploaded file must be an image.")9 unmodified linesresult = get_model_service().predict_image(image)result["filename"] = file.filenameresult["content_type"] = file.content_typereturn result, data@app.get("/")def root():return {"message": "Presence Detection API","docs": "/docs","model_path": str(MODEL_PATH.name),}@app.get("/health")def health():return {"status": "ok", "model_loaded": True}@app.get("/demo", response_class=HTMLResponse)def demo_page(request: Request):return templates.TemplateResponse(request,"demo.html",_build_demo_context(),)@app.post("/demo", response_class=HTMLResponse)async def demo_predict(request: Request, file: UploadFile = File(...)):try:result, data = await _predict_upload(file)except HTTPException as exc:return templates.TemplateResponse(request,"demo.html",_build_demo_context(error=exc.detail),status_code=exc.status_code,)pred_label = result["label"]pred_conf = result["probabilities"][pred_label]image_data_url = (f"data:{result['content_type']};base64,"f"{base64.b64encode(data).decode('ascii')}")return templates.TemplateResponse(request,"demo.html",_build_demo_context(image_data_url=image_data_url,result_label=pred_label,result_label_zh="有人" if pred_label == "person" else "正常",class_label=pred_label,confidence=f"{pred_conf * 100:.2f}%",acc=f"{pred_conf * 100:.2f}%",),)@app.post("/predict")async def predict(file: UploadFile = File(...)):result, _ = await _predict_upload(file)return result
17 unmodified lines1819202117 unmodified lines"torchvision>=0.25.0","tqdm>=4.67.3","ultralytics>=8.4.17",]17 unmodified lines181920212217 unmodified lines"torchvision>=0.25.0","tqdm>=4.67.3","ultralytics>=8.4.17","jinja2>=3.1.6",]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205<!DOCTYPE html><html lang="zh-Hant"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Presence Detection Demo</title> <style> :root { --panel-bg: #dbdbdb; --box-bg: #bcd1e5; --box-bg-strong: #b6cbe0; --line: #6f6f6f; --text: #4f4f4f; }
* { box-sizing: border-box; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #f2f2f2; color: var(--text); font-family: "Noto Sans TC", "PingFang TC", "Microsoft JhengHei", sans-serif; }
.panel { width: min(92vw, 680px); min-height: 520px; background: var(--panel-bg); border: 2px solid var(--line); padding: 52px 38px; display: flex; flex-direction: column; gap: 34px; }
.top-row { display: grid; grid-template-columns: minmax(220px, 1fr) 1fr; gap: 34px; align-items: center; }
.upload-wrap { display: flex; flex-direction: column; gap: 10px; }
.upload-box { width: 100%; aspect-ratio: 1.25 / 1; border: 2px solid var(--line); background: var(--box-bg); color: #111; display: grid; place-items: center; text-align: center; cursor: pointer; overflow: hidden; position: relative; font-size: 22px; }
.upload-box img { width: 100%; height: 100%; object-fit: contain; background: #fff; }
.upload-hint { font-size: 13px; color: #666; text-align: center; }
.stats { font-size: clamp(20px, 2.6vw, 30px); line-height: 1.35; letter-spacing: 0.2px; }
.stats .error { margin-top: 14px; color: #a22; font-size: 14px; line-height: 1.4; word-break: break-word; }
.actions { margin-top: 6px; display: grid; place-items: center; gap: 14px; }
.result-pill { width: min(100%, 320px); height: 88px; border: 2px solid var(--line); background: var(--box-bg-strong); display: grid; place-items: center; font-size: clamp(22px, 4.5vw, 36px); color: #4c4c4c; }
.submit-btn { width: min(100%, 320px); padding: 12px 16px; border: 2px solid var(--line); background: #e9edf1; color: #333; font-size: 16px; cursor: pointer; }
.submit-btn:hover { background: #f1f4f7; }
.file-input { display: none; }
@media (max-width: 640px) { .panel { min-height: auto; padding: 24px 18px; gap: 22px; }
.top-row { grid-template-columns: 1fr; gap: 18px; }
.upload-box { font-size: 18px; }
.stats { font-size: 22px; } } </style></head><body> <form class="panel" action="/demo" method="post" enctype="multipart/form-data"> <div class="top-row"> <div class="upload-wrap"> <label class="upload-box" for="fileInput" id="uploadBox"> {% if image_data_url %} <img src="{{ image_data_url }}" alt="Input image preview" id="previewImage"> {% else %} <span id="placeholderText">Input Image</span> <img src="" alt="Input image preview" id="previewImage" style="display:none;"> {% endif %} </label> <input class="file-input" id="fileInput" type="file" name="file" accept="image/*" required> <div class="upload-hint">點擊圖片區塊選擇檔案</div> </div>
<div class="stats"> <div>Class: {{ class_label }}</div> <div>Confidence: {{ confidence }}</div> <div>Acc: {{ acc }}</div> {% if error %} <div class="error">{{ error }}</div> {% endif %} </div> </div>
<div class="actions"> <div class="result-pill">{{ result_label_zh }}</div> <button class="submit-btn" type="submit">開始預測</button> </div> </form>
<script> const fileInput = document.getElementById("fileInput"); const previewImage = document.getElementById("previewImage"); const placeholderText = document.getElementById("placeholderText");
fileInput.addEventListener("change", (event) => { const file = event.target.files?.[0]; if (!file) return;
const reader = new FileReader(); reader.onload = () => { if (placeholderText) placeholderText.style.display = "none"; previewImage.src = reader.result; previewImage.style.display = "block"; }; reader.readAsDataURL(file); }); </script></body></html>1233 unmodified lines12341235123612371238123911 unmodified lines1251125212531254125512561233 unmodified linessource = { virtual = "." }dependencies = [{ name = "fastapi" },{ name = "matplotlib" },{ name = "numpy" },{ name = "opencv-python" },11 unmodified lines[package.metadata]requires-dist = [{ name = "fastapi", specifier = ">=0.133.1" },{ name = "matplotlib", specifier = ">=3.10.8" },{ name = "numpy", specifier = ">=2.4.2" },{ name = "opencv-python", specifier = ">=4.13.0.92" },1233 unmodified lines123412351236123712381239124011 unmodified lines12521253125412551256125712581233 unmodified linessource = { virtual = "." }dependencies = [{ name = "fastapi" },{ name = "jinja2" },{ name = "matplotlib" },{ name = "numpy" },{ name = "opencv-python" },11 unmodified lines[package.metadata]requires-dist = [{ name = "fastapi", specifier = ">=0.133.1" },{ name = "jinja2", specifier = ">=3.1.6" },{ name = "matplotlib", specifier = ">=3.10.8" },{ name = "numpy", specifier = ">=2.4.2" },{ name = "opencv-python", specifier = ">=4.13.0.92" },
app.py+81-14
pyproject.toml+1
templates/demo.htmlAdded+205
uv.lock+2