Dmitry1313 commited on
Commit
bd46e92
·
verified ·
1 Parent(s): c4950a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +210 -18
app.py CHANGED
@@ -1,24 +1,216 @@
1
- # Dockerfile
2
- FROM python:3.10-slim
 
 
3
 
4
- # Устанавливаем системные зависимости
5
- RUN apt-get update && apt-get install -y \
6
- libgl1-mesa-glx \
7
- libglib2.0-0 \
8
- && rm -rf /var/lib/apt/lists/*
9
 
10
- # Рабочая директория
11
- WORKDIR /app
12
 
13
- # Копируем зависимости
14
- COPY requirements.txt .
15
- RUN pip install --no-cache-dir -r requirements.txt
16
 
17
- # Копируем приложение
18
- COPY app.py .
19
 
20
- # Порт для FastAPI
21
- EXPOSE 7860
22
 
23
- # Запуск
24
- CMD ["python", "app.py"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import io
3
+ import logging
4
+ from typing import Optional, Dict, Any
5
 
6
+ import numpy as np
7
+ import cv2
8
+ from PIL import Image
9
+ from fastapi import FastAPI, File, UploadFile, HTTPException
10
+ from fastapi.responses import JSONResponse
11
 
12
+ # MediaPipe
13
+ import mediapipe as mp
14
 
15
+ # Настройка логирования
16
+ logging.basicConfig(level=logging.INFO)
17
+ logger = logging.getLogger(__name__)
18
 
19
+ app = FastAPI(title="AI Face Detection API", version="1.0.0")
 
20
 
21
+ # Инициализация MediaPipe (ленивая)
22
+ _face_detection = None
23
 
24
+ def get_face_detector():
25
+ """Ленивая инициализация детектора"""
26
+ global _face_detection
27
+ if _face_detection is None:
28
+ _face_detection = mp.solutions.face_detection.FaceDetection(
29
+ model_selection=1, # 1=full-range (до 5м)
30
+ min_detection_confidence=0.5
31
+ )
32
+ logger.info("✅ MediaPipe FaceDetection initialized")
33
+ return _face_detection
34
+
35
+
36
+ @app.get("/")
37
+ async def root():
38
+ """Health check"""
39
+ return {
40
+ "status": "ok",
41
+ "service": "AI Face Detection API",
42
+ "version": "1.0.0",
43
+ "endpoints": {
44
+ "detect": "POST /detect - Detect face in image",
45
+ "health": "GET /health - Health check"
46
+ }
47
+ }
48
+
49
+
50
+ @app.get("/health")
51
+ async def health():
52
+ """Detailed health check"""
53
+ try:
54
+ detector = get_face_detector()
55
+ return {"status": "healthy", "mediapipe": "ready"}
56
+ except Exception as e:
57
+ return {"status": "unhealthy", "error": str(e)}
58
+
59
+
60
+ @app.post("/detect")
61
+ async def detect_face(file: UploadFile = File(...)):
62
+ """
63
+ 🔍 Detect face in uploaded image
64
+
65
+ Request:
66
+ - file: image (PNG/JPEG)
67
+
68
+ Response:
69
+ {
70
+ "success": true,
71
+ "face": {
72
+ "x": int,
73
+ "y": int,
74
+ "width": int,
75
+ "height": int,
76
+ "score": float
77
+ },
78
+ "image_size": {"width": int, "height": int}
79
+ }
80
+ """
81
+ try:
82
+ # Читаем изображение
83
+ contents = await file.read()
84
+
85
+ # Конвертируем bytes → numpy → OpenCV
86
+ img_array = np.frombuffer(contents, np.uint8)
87
+ img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
88
+
89
+ if img is None:
90
+ raise HTTPException(status_code=400, detail="Failed to decode image")
91
+
92
+ h, w = img.shape[:2]
93
+ logger.info(f"📐 Processing image: {w}x{h}px")
94
+
95
+ # Детекция лица
96
+ detector = get_face_detector()
97
+ rgb_image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
98
+ results = detector.process(rgb_image)
99
+
100
+ if results.detections:
101
+ # Берём первое (самое крупное) лицо
102
+ detection = results.detections[0]
103
+ bbox = detection.location_data.relative_bounding_box
104
+
105
+ # Относительные → абсолютные координаты
106
+ x = max(0, int(bbox.xmin * w))
107
+ y = max(0, int(bbox.ymin * h))
108
+ width = min(w - x, int(bbox.width * w))
109
+ height = min(h - y, int(bbox.height * h))
110
+ score = detection.score[0] if detection.score else 0
111
+
112
+ logger.info(f"✅ Face detected: {width}x{height}px, score={score:.2f}")
113
+
114
+ return JSONResponse({
115
+ "success": True,
116
+ "face": {
117
+ "x": x,
118
+ "y": y,
119
+ "width": width,
120
+ "height": height,
121
+ "score": round(score, 3)
122
+ },
123
+ "image_size": {
124
+ "width": w,
125
+ "height": h
126
+ }
127
+ })
128
+ else:
129
+ logger.warning("⚠️ No faces detected")
130
+ return JSONResponse({
131
+ "success": False,
132
+ "error": "No face detected",
133
+ "image_size": {"width": w, "height": h}
134
+ }, status_code=404)
135
+
136
+ except HTTPException:
137
+ raise
138
+ except Exception as e:
139
+ logger.error(f"❌ Detection error: {type(e).__name__}: {e}")
140
+ raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")
141
+
142
+
143
+ @app.post("/detect-batch")
144
+ async def detect_faces_batch(files: list[UploadFile] = File(...)):
145
+ """
146
+ 🔍 Detect faces in multiple images (batch processing)
147
+
148
+ Request:
149
+ - files: multiple images
150
+
151
+ Response:
152
+ {
153
+ "results": [
154
+ {"filename": "img1.jpg", "face": {...}},
155
+ ...
156
+ ]
157
+ }
158
+ """
159
+ results = []
160
+
161
+ for file in files:
162
+ try:
163
+ contents = await file.read()
164
+ img_array = np.frombuffer(contents, np.uint8)
165
+ img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
166
+
167
+ if img is None:
168
+ results.append({"filename": file.filename, "error": "Decode failed"})
169
+ continue
170
+
171
+ h, w = img.shape[:2]
172
+ detector = get_face_detector()
173
+ rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
174
+ detection_results = detector.process(rgb)
175
+
176
+ if detection_results.detections:
177
+ det = detection_results.detections[0]
178
+ bbox = det.location_data.relative_bounding_box
179
+ x = max(0, int(bbox.xmin * w))
180
+ y = max(0, int(bbox.ymin * h))
181
+ width = min(w - x, int(bbox.width * w))
182
+ height = min(h - y, int(bbox.height * h))
183
+ score = det.score[0] if det.score else 0
184
+
185
+ results.append({
186
+ "filename": file.filename,
187
+ "face": {
188
+ "x": x, "y": y,
189
+ "width": width, "height": height,
190
+ "score": round(score, 3)
191
+ }
192
+ })
193
+ else:
194
+ results.append({
195
+ "filename": file.filename,
196
+ "error": "No face detected"
197
+ })
198
+
199
+ except Exception as e:
200
+ results.append({
201
+ "filename": file.filename,
202
+ "error": str(e)
203
+ })
204
+
205
+ return {"results": results}
206
+
207
+
208
+ if __name__ == "__main__":
209
+ import uvicorn
210
+ # Запуск на порту 7860 (стандарт для HF Spaces)
211
+ uvicorn.run(
212
+ "app:app",
213
+ host="0.0.0.0",
214
+ port=7860,
215
+ log_level="info"
216
+ )