Spaces:
Sleeping
Sleeping
File size: 6,219 Bytes
435ecd3 2d1688d 435ecd3 | 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 | """提供原页面和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'
@asynccontextmanager
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)
@app.get('/api/health')
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()
@app.post('/api/gesture')
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'}
@app.get('/')
def home():
"""显示与Static版相同的课程首页。"""
return FileResponse(ROOT / 'index.html', headers={'Cache-Control': 'no-cache'})
@app.get('/{file_name}')
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'})
|