Spaces:
Sleeping
Sleeping
FEAT: Add Dockerized FastAPI inference service
Browse files新增 FastAPI 人員存在偵測 API、模型載入服務與 uv 相依設定。\n加入 Dockerfile 與 Hugging Face Spaces 設定,並附上測試圖片。
Files changed (10)
- .gitignoreAdded+216
- .python-versionAdded+1
- DockerfileAdded+27
- app.py+53-5
- main.pyAdded+31
- model_service.pyAdded+65
- no_person.jpgAdded
- person.jpgAdded
- pyproject.tomlAdded+21
- uv.lockAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216# Byte-compiled / optimized / DLL files__pycache__/*.py[codz]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py.cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.# Pipfile.lock
# UV# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# uv.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control# poetry.lock# poetry.toml
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.# https://pdm-project.org/en/latest/usage/project/#working-with-version-control# pdm.lock# pdm.toml.pdm-python.pdm-build/
# pixi# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.# pixi.lock# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one# in the .venv directory. It is recommended not to include this directory in version control..pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# Redis*.rdb*.aof*.pid
# RabbitMQmnesia/rabbitmq/rabbitmq-data/
# ActiveMQactivemq-data/
# SageMath parsed files*.sage.py
# Environments.env.envrc.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.# .idea/
# Abstra# Abstra is an AI-powered process automation framework.# Ignore directories containing user credentials, local state, and settings.# Learn more at https://abstra.io/docs.abstra/
# Visual Studio Code# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore# and can be added to the global gitignore or merged into this file. However, if you prefer, # you could uncomment the following to ignore the entire vscode folder# .vscode/
# Ruff stuff:.ruff_cache/
# PyPI configuration file.pypirc
# Marimomarimo/_static/marimo/_lsp/__marimo__/
# Streamlit.streamlit/secrets.toml13.12123456789101112131415161718192021222324252627FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ UV_LINK_MODE=copy
WORKDIR /app
# Install system deps commonly needed by Pillow/torchvision runtime on Spaces.RUN apt-get update && apt-get install -y --no-install-recommends \ libglib2.0-0 \ libsm6 \ libxext6 \ libxrender1 \ curl \ && rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir uv
COPY pyproject.toml uv.lock ./RUN uv sync --frozen --no-dev
COPY . .
EXPOSE 7860
CMD ["sh", "-c", "uv run uvicorn app:app --host 0.0.0.0 --port ${PORT:-7860}"]112334456677891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import gradio as grfrom contextlib import asynccontextmanagerfrom io import BytesIO
def greet(name): return "Hello " + name + "!!"from fastapi import FastAPI, File, HTTPException, UploadFilefrom PIL import Image, UnidentifiedImageError
demo = gr.Interface(fn=greet, inputs="text", outputs="text")demo.launch()from model_service import MODEL_PATH, get_model_service
@asynccontextmanagerasync def lifespan(_: FastAPI): # Warm up model on startup so the first request is not slow. get_model_service() yield
app = FastAPI( title="Presence Detection API", description="Detect whether an image contains a person.", version="0.1.0", lifespan=lifespan,)
@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.")
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 exc
result = get_model_service().predict_image(image) result["filename"] = file.filename result["content_type"] = file.content_type return result12345678910111213141516171819202122232425262728293031from pathlib import Pathfrom PIL import Image
from model_service import MODEL_PATH, get_model_service
IMAGE_PATH = Path("person.jpg")# IMAGE_PATH = Path("no_person.jpg")
def main(): if not IMAGE_PATH.exists(): raise SystemExit(f"Image not found: {IMAGE_PATH}")
service = get_model_service() print(f"[INFO] device={service.device}") print(f"[INFO] model={MODEL_PATH}") print(f"[INFO] image={IMAGE_PATH}")
img = Image.open(IMAGE_PATH).convert("RGB") result = service.predict_image(img)
print("\n========== RESULT ==========") print(f"Prediction: {result['label']}") print(f"P(no_person) = {result['probabilities']['no_person']:.4f}") print(f"P(person) = {result['probabilities']['person']:.4f}") print("============================")
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465from functools import lru_cachefrom pathlib import Path
import torchimport torch.nn as nnimport torchvision.transforms as Tfrom PIL import Imagefrom torchvision import models
BASE_DIR = Path(__file__).resolve().parentMODEL_PATH = BASE_DIR / "best_global_model_presence.pt"CLASS_NAMES = ["no_person", "person"]
def build_resnet18(num_classes: int = 2) -> nn.Module: # We load task-specific weights from `best_global_model_presence.pt`, so no # pretrained backbone download is needed at runtime. model = models.resnet18(weights=None) in_features = model.fc.in_features model.fc = nn.Linear(in_features, num_classes) return model
class PresenceModelService: def __init__(self, model_path: Path): if not model_path.exists(): raise FileNotFoundError(f"Model not found: {model_path}")
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.model = build_resnet18(num_classes=2).to(self.device)
state = torch.load(model_path, map_location="cpu") self.model.load_state_dict(state, strict=True) self.model.eval()
self.transform = T.Compose( [ T.Resize((224, 224)), T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), ] )
def predict_image(self, image: Image.Image) -> dict: x = self.transform(image).unsqueeze(0).to(self.device)
with torch.no_grad(): logits = self.model(x) probs = torch.softmax(logits, dim=-1)[0] pred_idx = int(torch.argmax(probs).item())
probabilities = { CLASS_NAMES[i]: round(float(probs[i].item()), 6) for i in range(len(CLASS_NAMES)) } return { "label": CLASS_NAMES[pred_idx], "prediction_index": pred_idx, "probabilities": probabilities, }
@lru_cache(maxsize=1)def get_model_service() -> PresenceModelService: return PresenceModelService(MODEL_PATH)123456789101112131415161718192021[project]name = "securemlapi"version = "0.1.0"description = "Add your description here"readme = "README.md"requires-python = ">=3.12"dependencies = [ "fastapi>=0.133.1", "uvicorn>=0.41.0", "python-multipart>=0.0.20", "matplotlib>=3.10.8", "numpy>=2.4.2", "opencv-python>=4.13.0.92", "pandas>=3.0.1", "pillow>=12.1.1", "scikit-learn>=1.8.0", "torch>=2.10.0", "torchvision>=0.25.0", "tqdm>=4.67.3", "ultralytics>=8.4.17",].gitignoreAdded+216
.python-versionAdded+1
DockerfileAdded+27
app.py+53-5
main.pyAdded+31
model_service.pyAdded+65
no_person.jpgAdded

person.jpgAdded

pyproject.tomlAdded+21
uv.lockAdded