Spaces:
Sleeping
Sleeping
Download server.py from ZevonLew/Image_Recognition: direct link, hf CLI and curl.
- Browser
- Download file 6.22 kB
-
https://huggingface.co/spaces/ZevonLew/Image_Recognition/resolve/main/server.py
- Command line
-
hf download hf://spaces/ZevonLew/Image_Recognition/server.py
-
curl -L -o server.py https://huggingface.co/spaces/ZevonLew/Image_Recognition/resolve/main/server.py
6.22 kB
| """提供原页面和MediaPipe CPU兼容接口;图片仅在本次请求内存中处理。""" | |
| from contextlib import asynccontextmanager | |
| from io import BytesIO | |
| from pathlib import Path | |
| from threading import Lock | |
| import asyncio | |
| import math | |
| import mediapipe as mp | |
| import numpy as np | |
| from fastapi import FastAPI, HTTPException, Request | |
| from fastapi.responses import FileResponse, JSONResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from PIL import Image, ImageOps, UnidentifiedImageError | |
| ROOT = Path(__file__).resolve().parent | |
| MAX_BYTES = 16 * 1024 * 1024 | |
| MAX_PIXELS = 24_000_000 | |
| Image.MAX_IMAGE_PIXELS = MAX_PIXELS | |
| recognizer = None | |
| recognizer_lock = Lock() | |
| MODEL_NAME = 'MediaPipe Tasks Vision 0.10.18' | |
| RELEASE = '20261013-gradio-1' | |
| async def lifespan(application): | |
| """启动时加载同一task文件;显式指定CPU并在服务结束时释放。""" | |
| global recognizer | |
| options = mp.tasks.vision.GestureRecognizerOptions( | |
| base_options=mp.tasks.BaseOptions( | |
| model_asset_path=str(ROOT / 'models/gesture_recognizer.task'), | |
| delegate=mp.tasks.BaseOptions.Delegate.CPU), | |
| running_mode=mp.tasks.vision.RunningMode.IMAGE, | |
| num_hands=2) | |
| recognizer = mp.tasks.vision.GestureRecognizer.create_from_options(options) | |
| try: | |
| yield | |
| finally: | |
| recognizer.close() | |
| recognizer = None | |
| app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) | |
| def health(): | |
| """便于部署后确认CPU模型已就绪;此接口不接收图片。""" | |
| return {'ready': recognizer is not None, 'gesture_cpu': True, | |
| 'model': MODEL_NAME, 'version': RELEASE, 'sdk': 'gradio'} | |
| def infer_gesture(payload, threshold): | |
| """串行调用非线程安全的Tasks对象;解码、推理及结果均不落盘。""" | |
| if not recognizer_lock.acquire(blocking=False): | |
| raise HTTPException(503, 'The Space CPU is busy. Wait a moment and retry.') | |
| try: | |
| try: | |
| with Image.open(BytesIO(payload)) as decoded: | |
| if decoded.format not in ('PNG', 'JPEG', 'WEBP'): | |
| raise HTTPException(415, 'Use a PNG, JPEG or WebP image.') | |
| if decoded.width * decoded.height > MAX_PIXELS: | |
| raise HTTPException(413, 'Use an image of at most 24 megapixels.') | |
| rgb = np.ascontiguousarray(np.asarray(ImageOps.exif_transpose(decoded).convert('RGB'))) | |
| except (UnidentifiedImageError, OSError, ValueError, Image.DecompressionBombError, Image.DecompressionBombWarning): | |
| raise HTTPException(400, 'Could not decode this image. Choose a valid image and retry.') | |
| raw = recognizer.recognize(mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)) | |
| hands = [] | |
| for i, points in enumerate(raw.hand_landmarks): | |
| gesture = raw.gestures[i][0] if raw.gestures[i] else None | |
| candidate = gesture.category_name if gesture else 'None' | |
| score = float(gesture.score) if gesture else 0.0 | |
| accepted = bool(gesture and candidate != 'None' and score >= threshold) | |
| handedness = raw.handedness[i][0].category_name if raw.handedness[i] else 'Unknown' | |
| hands.append({'label': candidate if accepted else 'Unrecognized', | |
| 'candidate': candidate, 'score': score, 'accepted': accepted, | |
| 'handedness': handedness, | |
| 'points': [{'x': p.x, 'y': p.y, 'z': p.z} for p in points]}) | |
| return {'task': 'gesture', 'model': MODEL_NAME, 'backend': 'Space CPU', 'serverBuild': RELEASE, | |
| 'threshold': threshold, 'hands': hands, | |
| 'processedSize': {'width': int(rgb.shape[1]), 'height': int(rgb.shape[0])}, | |
| 'note': 'Static gesture categories; not sign-language translation.' if hands else | |
| 'No hand detected. Try a clear, complete hand on a simple background.'} | |
| finally: | |
| recognizer_lock.release() | |
| async def gesture(request: Request, threshold: float = 0.6): | |
| """限制上传大小和阈值;CPU推理移入线程,健康检查和页面读取仍可响应。""" | |
| if not math.isfinite(threshold) or not 0 <= threshold <= 1: | |
| raise HTTPException(400, 'The gesture score threshold must be between 0 and 1.') | |
| payload = bytearray() | |
| async for chunk in request.stream(): | |
| payload.extend(chunk) | |
| if len(payload) > MAX_BYTES: | |
| raise HTTPException(413, 'Use an image under 16 MB.') | |
| if not payload: | |
| raise HTTPException(400, 'Choose an image before running recognition.') | |
| try: | |
| result = await asyncio.to_thread(infer_gesture, payload, threshold) | |
| except HTTPException: | |
| raise | |
| except Exception: | |
| # 不把图像内容、请求体或后端调用栈写入日志/返回给客户端。 | |
| raise HTTPException(500, 'The CPU model could not complete this run. Retry with a clear hand image.') | |
| return JSONResponse(result, headers={'Cache-Control': 'no-store'}) | |
| # 只暴露必需的静态目录和白名单文件,仓库其余内容不对外提供。 | |
| for directory in ('vendor', 'models', 'samples'): | |
| app.mount('/' + directory, StaticFiles(directory=ROOT / directory), name=directory) | |
| # 分组图库模块是公开课程资产,仍使用白名单而不暴露任意仓库文件。 | |
| PUBLIC_FILES = {'index.html', 'style.css', 'app.js', 'recognizers.js', 'sample_catalog.js', | |
| 'how-to-start.html', 'how-to-start.pdf', 'THIRD_PARTY_NOTICES.md'} | |
| def home(): | |
| """显示与Static版相同的课程首页。""" | |
| return FileResponse(ROOT / 'index.html', headers={'Cache-Control': 'no-cache'}) | |
| def public_file(file_name: str): | |
| """模块使用版本参数;HTML和脚本不强缓存,方便后续替换补丁。""" | |
| if file_name not in PUBLIC_FILES: | |
| raise HTTPException(404, 'Not found') | |
| return FileResponse(ROOT / file_name, headers={'Cache-Control': 'no-cache'}) | |