Spaces:
Sleeping
Sleeping
feat: improve demo model selection workflow
Browse files新增 demo 頁面的模型下拉選單,支援在同一張圖片上切換不同模型重新推論。
調整圖片預覽縮放與顯示尺寸,並放寬 multipart 上傳大小限制,避免大圖被 1MB 預設限制擋下。
Files changed (2)
- app.py+106-17
- templates/demo.html+66-7
1 unmodified line234567891011121314151622 unmodified lines39404142434445464748495051525354555657585960616263646566676820 unmodified lines899091929394959697989910010110213 unmodified lines1161171181191201211221231241251261 unmodified linefrom 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 get_model_config, get_model_serviceBASE_DIR = Path(__file__).resolve().parenttemplates = Jinja2Templates(directory=str(BASE_DIR / "templates"))ACTIVE_MODEL_CONFIG = get_model_config()22 unmodified lines"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.")data = await file.read()if not data:raise HTTPException(status_code=400, detail="Uploaded file is empty.")try:image = Image.open(BytesIO(data)).convert("RGB")except UnidentifiedImageError as exc:raise HTTPException(status_code=400, detail="Invalid image file.") from excresult = get_model_service().predict_image(image)result["filename"] = file.filenameresult["content_type"] = file.content_typereturn result, data@app.get("/")def root():return {20 unmodified lines@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,)13 unmodified linesclass_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 result1 unmodified line2345678910111213141516171822 unmodified lines414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115220 unmodified lines17317417517617717817918018118218318418518618718818913 unmodified lines2032042052062072082092102112122132142151 unmodified linefrom contextlib import asynccontextmanagerfrom io import BytesIOfrom pathlib import Pathfrom urllib.parse import unquote_to_bytesfrom fastapi import FastAPI, HTTPException, Request, UploadFilefrom fastapi.responses import HTMLResponsefrom fastapi.templating import Jinja2Templatesfrom PIL import Image, UnidentifiedImageErrorfrom model_service import MODEL_CONFIGS, get_model_config, get_model_serviceBASE_DIR = Path(__file__).resolve().parentMAX_UPLOAD_SIZE = 10 * 1024 * 1024templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))ACTIVE_MODEL_CONFIG = get_model_config()22 unmodified lines"confidence": "-","acc": "-","error": None,"selected_model": ACTIVE_MODEL_CONFIG.name,"model_options": [{"name": config.name,"backend": config.backend,"path": config.model_path.name,}for config in MODEL_CONFIGS.values()],}context.update(overrides)return contextdef _parse_data_url(data_url: str) -> tuple[bytes, str]:if not data_url.startswith("data:") or "," not in data_url:raise HTTPException(status_code=400, detail="Invalid preview image data.")header, encoded = data_url.split(",", 1)content_type = header[5:].split(";")[0] or "image/png"if not content_type.startswith("image/"):raise HTTPException(status_code=400, detail="Preview data must be an image.")if ";base64" in header:try:return base64.b64decode(encoded), content_typeexcept ValueError as exc:raise HTTPException(status_code=400, detail="Invalid preview image data.") from excreturn unquote_to_bytes(encoded), content_typeasync def _read_image_data(file: UploadFile | None,existing_image_data_url: str | None = None,) -> tuple[bytes, str, str | None]:if file and file.filename:if not file.content_type or not file.content_type.startswith("image/"):raise HTTPException(status_code=400, detail="Uploaded file must be an image.")data = await file.read()if not data:raise HTTPException(status_code=400, detail="Uploaded file is empty.")return data, file.content_type, file.filenameif existing_image_data_url:data, content_type = _parse_data_url(existing_image_data_url)if not data:raise HTTPException(status_code=400, detail="Preview image is empty.")return data, content_type, Noneraise HTTPException(status_code=400, detail="Please upload an image first.")async def _predict_upload(file: UploadFile | None,model_name: str | None = None,existing_image_data_url: str | None = None,) -> tuple[dict, bytes]:data, content_type, filename = await _read_image_data(file, existing_image_data_url)try:image = Image.open(BytesIO(data)).convert("RGB")except (UnidentifiedImageError, OSError) as exc:raise HTTPException(status_code=400, detail="Invalid image file.") from exctry:result = get_model_service(model_name).predict_image(image)except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from excresult["filename"] = filenameresult["content_type"] = content_typereturn result, dataasync def _parse_demo_form(request: Request) -> tuple[UploadFile | None, str, str | None]:try:form = await request.form(max_part_size=MAX_UPLOAD_SIZE)except HTTPException:raiseexcept Exception as exc:raise HTTPException(status_code=400, detail=str(exc)) from excfile_value = form.get("file")file = file_value if isinstance(file_value, UploadFile) else Nonemodel_name = str(form.get("model_name") or ACTIVE_MODEL_CONFIG.name)existing_image_data_url = form.get("existing_image_data_url")if existing_image_data_url is not None:existing_image_data_url = str(existing_image_data_url)return file, model_name, existing_image_data_urlasync def _parse_predict_form(request: Request) -> tuple[UploadFile | None, str]:try:form = await request.form(max_part_size=MAX_UPLOAD_SIZE)except HTTPException:raiseexcept Exception as exc:raise HTTPException(status_code=400, detail=str(exc)) from excfile_value = form.get("file")file = file_value if isinstance(file_value, UploadFile) else Nonemodel_name = str(form.get("model_name") or ACTIVE_MODEL_CONFIG.name)return file, model_name@app.get("/")def root():return {20 unmodified lines@app.post("/demo", response_class=HTMLResponse)async def demo_predict(request: Request,):file, model_name, existing_image_data_url = await _parse_demo_form(request)try:result, data = await _predict_upload(file, model_name, existing_image_data_url)except HTTPException as exc:return templates.TemplateResponse(request,"demo.html",_build_demo_context(error=exc.detail, selected_model=model_name),status_code=exc.status_code,)13 unmodified linesclass_label=pred_label,confidence=f"{pred_conf * 100:.2f}%",acc=f"{pred_conf * 100:.2f}%",selected_model=result["model_name"],),)@app.post("/predict")async def predict(request: Request):file, model_name = await _parse_predict_form(request)result, _ = await _predict_upload(file, model_name)return result
50 unmodified lines51525354555657585960616263646566676869707172737467 unmodified lines1421431441451461471481491502 unmodified lines1531541551561571581591602 unmodified lines16316416516616716816917017117217310 unmodified lines1841851861871881891901911924 unmodified lines19719819920020120220320420550 unmodified linesgap: 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;}67 unmodified lines}.upload-box {font-size: 18px;}.stats {font-size: 22px;}2 unmodified lines</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">2 unmodified lines<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>10 unmodified lines</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];4 unmodified linesif (placeholderText) placeholderText.style.display = "none";previewImage.src = reader.result;previewImage.style.display = "block";};reader.readAsDataURL(file);});</script></body></html>50 unmodified lines5152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910067 unmodified lines1681691701711721731741751761771781791801811821831842 unmodified lines1871881891901911921931941951961971981992002012022032042052062 unmodified lines20921021121221321421521621721821922010 unmodified lines2312322332342352362372382392402414 unmodified lines24624724824925025125225325425525625725825926026126226326450 unmodified linesgap: 10px;}.field-group {display: flex;flex-direction: column;gap: 8px;}.field-label {font-size: 14px;color: #555;letter-spacing: 0.2px;}.model-select {width: 100%;padding: 11px 12px;border: 2px solid var(--line);background: #edf2f7;color: #333;font-size: 15px;}.upload-box {width: 100%;min-height: 280px;border: 2px solid var(--line);background: var(--box-bg);color: #111;display: flex;align-items: center;justify-content: center;padding: 14px;text-align: center;cursor: pointer;position: relative;font-size: 22px;}.upload-box img {width: min(100%, 280px);height: 280px;min-width: 220px;min-height: 220px;max-width: 100%;max-height: 320px;object-fit: contain;background: #fff;}67 unmodified lines}.upload-box {min-height: 220px;font-size: 18px;}.upload-box img {width: min(100%, 220px);height: 220px;min-width: 160px;min-height: 160px;}.stats {font-size: 22px;}2 unmodified lines</head><body><form class="panel" action="/demo" method="post" enctype="multipart/form-data"><input type="hidden" name="existing_image_data_url" id="existingImageDataUrl" value="{{ image_data_url or '' }}"><div class="top-row"><div class="upload-wrap"><div class="field-group"><label class="field-label" for="modelSelect">推論模型</label><select class="model-select" id="modelSelect" name="model_name">{% for model in model_options %}<option value="{{ model.name }}" {% if model.name == selected_model %}selected{% endif %}>{{ model.name }} ({{ model.backend }})</option>{% endfor %}</select></div><label class="upload-box" for="fileInput" id="uploadBox">{% if image_data_url %}<img src="{{ image_data_url }}" alt="Input image preview" id="previewImage">2 unmodified lines<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/*"><div class="upload-hint">點擊圖片區塊選擇檔案</div></div><div class="stats"><div>Model: {{ selected_model }}</div><div>Class: {{ class_label }}</div><div>Confidence: {{ confidence }}</div><div>Acc: {{ acc }}</div>10 unmodified lines</form><script>const form = document.querySelector(".panel");const fileInput = document.getElementById("fileInput");const previewImage = document.getElementById("previewImage");const placeholderText = document.getElementById("placeholderText");const existingImageDataUrl = document.getElementById("existingImageDataUrl");fileInput.addEventListener("change", (event) => {const file = event.target.files?.[0];4 unmodified linesif (placeholderText) placeholderText.style.display = "none";previewImage.src = reader.result;previewImage.style.display = "block";existingImageDataUrl.value = reader.result;};reader.readAsDataURL(file);});form.addEventListener("submit", (event) => {const hasNewFile = Boolean(fileInput.files?.length);const hasExistingImage = Boolean(existingImageDataUrl.value);if (!hasNewFile && !hasExistingImage) {event.preventDefault();alert("請先上傳圖片。");}});</script></body></html>
app.py+106-17
templates/demo.html+66-7