Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,6 +12,7 @@ import uuid
|
|
| 12 |
import shutil
|
| 13 |
from datetime import datetime
|
| 14 |
from typing import Dict, List, Optional, Tuple, Any
|
|
|
|
| 15 |
|
| 16 |
import numpy as np
|
| 17 |
import cv2
|
|
@@ -21,39 +22,48 @@ from flask_cors import CORS
|
|
| 21 |
from flask_compress import Compress
|
| 22 |
from werkzeug.security import generate_password_hash, check_password_hash
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
| 25 |
|
|
|
|
| 26 |
app = Flask(__name__)
|
| 27 |
app.secret_key = os.environ.get('SECRET_KEY', 'yogamate-secret-key-change-in-production')
|
| 28 |
CORS(app, supports_credentials=True)
|
| 29 |
Compress(app)
|
| 30 |
|
| 31 |
-
|
| 32 |
-
level=logging.INFO,
|
| 33 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 34 |
-
)
|
| 35 |
-
|
| 36 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 37 |
-
# Configuration
|
| 38 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
CONFIG = {
|
| 40 |
'IMAGE_SIZE': (256, 192),
|
| 41 |
'JPEG_QUALITY': 50,
|
| 42 |
-
'MIN_DETECTION_CONFIDENCE': 0.5,
|
| 43 |
-
'MIN_TRACKING_CONFIDENCE': 0.3,
|
| 44 |
-
'MODEL_COMPLEXITY': 0,
|
| 45 |
-
'SMOOTH_LANDMARKS':
|
| 46 |
-
'REFERENCE_FILE': 'pose_reference.json',
|
| 47 |
-
'PERFECT_THRESHOLD': 80,
|
| 48 |
-
'GOOD_THRESHOLD': 65,
|
| 49 |
-
'USER_DATA_DIR': 'user_data',
|
| 50 |
-
'TEMP_UPLOAD_DIR': 'temp_uploads',
|
| 51 |
-
'YOGA_DIR': 'yoga',
|
|
|
|
|
|
|
| 52 |
}
|
| 53 |
|
| 54 |
-
#
|
| 55 |
-
# User Store
|
| 56 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 57 |
USER_STORE = 'users.json'
|
| 58 |
|
| 59 |
def load_users():
|
|
@@ -66,9 +76,7 @@ def save_users(users):
|
|
| 66 |
with open(USER_STORE, 'w') as f:
|
| 67 |
json.dump(users, f, indent=2)
|
| 68 |
|
| 69 |
-
#
|
| 70 |
-
# MediaPipe Setup
|
| 71 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 72 |
mp_pose = mp.solutions.pose
|
| 73 |
mp_drawing = mp.solutions.drawing_utils
|
| 74 |
|
|
@@ -82,21 +90,37 @@ pose_live = mp_pose.Pose(
|
|
| 82 |
smooth_segmentation=False
|
| 83 |
)
|
| 84 |
|
| 85 |
-
#
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
class ImageProcessor:
|
| 90 |
"""Handle image processing and validation."""
|
| 91 |
-
|
| 92 |
ALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.webp'}
|
| 93 |
MAX_FILE_SIZE = 10 * 1024 * 1024
|
| 94 |
REQUIRED_IMAGES = 5
|
| 95 |
-
|
| 96 |
def __init__(self, upload_dir: str = "temp_uploads"):
|
| 97 |
self.upload_dir = upload_dir
|
| 98 |
os.makedirs(upload_dir, exist_ok=True)
|
| 99 |
-
|
| 100 |
def save_temp_image(self, file_data: bytes, original_filename: str) -> Optional[str]:
|
| 101 |
logger.info(f"π₯ Saving temp image: {original_filename}")
|
| 102 |
try:
|
|
@@ -104,15 +128,14 @@ class ImageProcessor:
|
|
| 104 |
if ext not in self.ALLOWED_EXTENSIONS:
|
| 105 |
ext = 'jpg'
|
| 106 |
logger.info(f"π Extension changed to {ext}")
|
| 107 |
-
|
| 108 |
filename = f"{uuid.uuid4()}.{ext}"
|
| 109 |
file_path = os.path.join(self.upload_dir, filename)
|
| 110 |
-
|
| 111 |
with open(file_path, 'wb') as f:
|
| 112 |
f.write(file_data)
|
| 113 |
logger.info(f"πΎ File written to {file_path} ({len(file_data)} bytes)")
|
| 114 |
-
|
| 115 |
-
# Validate image
|
| 116 |
try:
|
| 117 |
import PIL.Image
|
| 118 |
img = PIL.Image.open(file_path)
|
|
@@ -123,11 +146,11 @@ class ImageProcessor:
|
|
| 123 |
os.remove(file_path)
|
| 124 |
logger.error(f"β Image validation failed: {e}")
|
| 125 |
return None
|
| 126 |
-
|
| 127 |
except Exception as e:
|
| 128 |
logger.error(f"β Error saving temp image: {e}")
|
| 129 |
return None
|
| 130 |
-
|
| 131 |
def delete_temp_file(self, file_path: str) -> bool:
|
| 132 |
try:
|
| 133 |
if os.path.exists(file_path):
|
|
@@ -137,7 +160,7 @@ class ImageProcessor:
|
|
| 137 |
except Exception as e:
|
| 138 |
logger.error(f"Error deleting temp file: {e}")
|
| 139 |
return False
|
| 140 |
-
|
| 141 |
def cleanup_temp_dir(self):
|
| 142 |
import time
|
| 143 |
now = time.time()
|
|
@@ -154,22 +177,21 @@ class ImageProcessor:
|
|
| 154 |
|
| 155 |
class CustomPoseManager:
|
| 156 |
"""Manage user-specific custom poses."""
|
| 157 |
-
|
| 158 |
def __init__(self, base_dir: str = "user_data"):
|
| 159 |
self.base_dir = base_dir
|
| 160 |
os.makedirs(self.base_dir, exist_ok=True)
|
| 161 |
-
|
| 162 |
def get_user_dir(self, user_id: str) -> str:
|
| 163 |
return os.path.join(self.base_dir, user_id)
|
| 164 |
-
|
| 165 |
def get_custom_poses_path(self, user_id: str) -> str:
|
| 166 |
return os.path.join(self.get_user_dir(user_id), "custom_poses.json")
|
| 167 |
-
|
| 168 |
def get_upload_dir(self, user_id: str, pose_id: str) -> str:
|
| 169 |
path = os.path.join(self.get_user_dir(user_id), "images", pose_id)
|
| 170 |
os.makedirs(path, exist_ok=True)
|
| 171 |
return path
|
| 172 |
-
|
| 173 |
def load_custom_poses(self, user_id: str) -> Dict:
|
| 174 |
path = self.get_custom_poses_path(user_id)
|
| 175 |
if os.path.exists(path):
|
|
@@ -181,7 +203,7 @@ class CustomPoseManager:
|
|
| 181 |
except Exception as e:
|
| 182 |
logger.error(f"Error loading custom poses: {e}")
|
| 183 |
return {}
|
| 184 |
-
|
| 185 |
def save_custom_poses(self, user_id: str, poses: Dict) -> bool:
|
| 186 |
path = self.get_custom_poses_path(user_id)
|
| 187 |
try:
|
|
@@ -193,17 +215,17 @@ class CustomPoseManager:
|
|
| 193 |
except Exception as e:
|
| 194 |
logger.error(f"Error saving custom poses: {e}")
|
| 195 |
return False
|
| 196 |
-
|
| 197 |
def add_custom_pose(self, user_id: str, pose_id: str, reference: Dict, images: List[str]) -> bool:
|
| 198 |
logger.info(f"π Adding custom pose {pose_id} for user {user_id[:8]}")
|
| 199 |
poses = self.load_custom_poses(user_id)
|
| 200 |
-
|
| 201 |
if pose_id in poses:
|
| 202 |
logger.warning(f"β οΈ Pose {pose_id} already exists, overwriting")
|
| 203 |
-
|
| 204 |
poses[pose_id] = reference
|
| 205 |
logger.info(f"π Reference data for {pose_id}: angles={len(reference.get('angles', []))} joints")
|
| 206 |
-
|
| 207 |
if images:
|
| 208 |
upload_dir = self.get_upload_dir(user_id, pose_id)
|
| 209 |
logger.info(f"π Saving {len(images)} images to {upload_dir}")
|
|
@@ -216,19 +238,19 @@ class CustomPoseManager:
|
|
| 216 |
logger.warning(f"β οΈ Image {img_path} not found, skipping")
|
| 217 |
else:
|
| 218 |
logger.info("βΉοΈ No images to copy (they are deleted after processing)")
|
| 219 |
-
|
| 220 |
success = self.save_custom_poses(user_id, poses)
|
| 221 |
if success:
|
| 222 |
logger.info(f"β
Custom poses saved (total: {len(poses)})")
|
| 223 |
else:
|
| 224 |
logger.error("β Failed to save custom poses")
|
| 225 |
return success
|
| 226 |
-
|
| 227 |
def get_custom_pose_images(self, user_id: str, pose_id: str) -> List[str]:
|
| 228 |
upload_dir = self.get_upload_dir(user_id, pose_id)
|
| 229 |
if not os.path.exists(upload_dir):
|
| 230 |
return []
|
| 231 |
-
|
| 232 |
images = []
|
| 233 |
for f in sorted(os.listdir(upload_dir)):
|
| 234 |
if f.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')):
|
|
@@ -238,7 +260,6 @@ class CustomPoseManager:
|
|
| 238 |
|
| 239 |
class PoseGenerator:
|
| 240 |
"""Generate pose references from images."""
|
| 241 |
-
|
| 242 |
def __init__(self):
|
| 243 |
self.pose = mp_pose.Pose(
|
| 244 |
static_image_mode=True,
|
|
@@ -251,9 +272,9 @@ class PoseGenerator:
|
|
| 251 |
(11, 0, 12), (13, 11, 23), (14, 12, 24), (15, 13, 11),
|
| 252 |
(16, 14, 12), (25, 23, 24), (26, 24, 23),
|
| 253 |
]
|
| 254 |
-
self.default_weights = [1.0, 1.0, 1.2, 1.2, 1.0, 1.0, 0.8, 0.8,
|
| 255 |
0.8, 1.0, 1.0, 0.7, 0.7, 0.8, 0.8]
|
| 256 |
-
|
| 257 |
def _calculate_angle(self, a, b, c):
|
| 258 |
a, b, c = np.array(a), np.array(b), np.array(c)
|
| 259 |
radians = np.arctan2(c[1] - b[1], c[0] - b[0]) - np.arctan2(a[1] - b[1], a[0] - b[0])
|
|
@@ -261,7 +282,7 @@ class PoseGenerator:
|
|
| 261 |
if angle > 180:
|
| 262 |
angle = 360 - angle
|
| 263 |
return angle
|
| 264 |
-
|
| 265 |
def extract_landmarks(self, image_path: str) -> Optional[Dict]:
|
| 266 |
logger.info(f"π Extracting landmarks from {image_path}")
|
| 267 |
try:
|
|
@@ -269,47 +290,47 @@ class PoseGenerator:
|
|
| 269 |
if img is None:
|
| 270 |
logger.error(f"β Could not read image: {image_path}")
|
| 271 |
return None
|
| 272 |
-
|
| 273 |
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 274 |
results = self.pose.process(rgb)
|
| 275 |
-
|
| 276 |
if not results.pose_landmarks:
|
| 277 |
logger.warning(f"β οΈ No pose detected in {image_path}")
|
| 278 |
return None
|
| 279 |
-
|
| 280 |
landmarks = [[lm.x, lm.y] for lm in results.pose_landmarks.landmark]
|
| 281 |
logger.info(f"β
Detected {len(landmarks)} landmarks")
|
| 282 |
-
|
| 283 |
angles = []
|
| 284 |
for a, b, c in self.joint_pairs:
|
| 285 |
if a >= len(landmarks) or b >= len(landmarks) or c >= len(landmarks):
|
| 286 |
logger.warning(f"β οΈ Landmark index out of range for {a},{b},{c}")
|
| 287 |
return None
|
| 288 |
angles.append(self._calculate_angle(landmarks[a], landmarks[b], landmarks[c]))
|
| 289 |
-
|
| 290 |
logger.info(f"β
Extracted {len(angles)} angles")
|
| 291 |
return {
|
| 292 |
'landmarks': landmarks,
|
| 293 |
'angles': angles,
|
| 294 |
'confidence': results.pose_landmarks.landmark[0].visibility
|
| 295 |
}
|
| 296 |
-
|
| 297 |
except Exception as e:
|
| 298 |
logger.error(f"β Error extracting landmarks: {e}")
|
| 299 |
return None
|
| 300 |
-
|
| 301 |
def calculate_tolerances(self, angle_lists: List[List[float]]) -> List[float]:
|
| 302 |
angle_array = np.array(angle_lists)
|
| 303 |
std_devs = np.std(angle_array, axis=0)
|
| 304 |
return [max(5, min(25, std * 2)) for std in std_devs]
|
| 305 |
-
|
| 306 |
def compare_similarity(self, landmarks_list: List[List[List[float]]]) -> float:
|
| 307 |
if len(landmarks_list) < 2:
|
| 308 |
return 1.0
|
| 309 |
-
|
| 310 |
arrays = [np.array(lm) for lm in landmarks_list]
|
| 311 |
similarities = []
|
| 312 |
-
|
| 313 |
for i in range(len(arrays)):
|
| 314 |
for j in range(i + 1, len(arrays)):
|
| 315 |
if arrays[i].shape != arrays[j].shape:
|
|
@@ -317,36 +338,36 @@ class PoseGenerator:
|
|
| 317 |
diff = np.mean((arrays[i] - arrays[j]) ** 2)
|
| 318 |
sim = max(0, 1 - (diff * 5))
|
| 319 |
similarities.append(sim)
|
| 320 |
-
|
| 321 |
return float(np.mean(similarities)) if similarities else 0.0
|
| 322 |
-
|
| 323 |
def generate_pose_reference(self, image_paths: List[str], pose_name: str,
|
| 324 |
difficulty: str = "Beginner", category: str = "General") -> Optional[Dict]:
|
| 325 |
logger.info(f"π Generating reference for '{pose_name}' with {len(image_paths)} images")
|
| 326 |
if len(image_paths) != 5:
|
| 327 |
return {'error': f'Expected 5 images, got {len(image_paths)}'}
|
| 328 |
-
|
| 329 |
landmarks_list = []
|
| 330 |
angle_lists = []
|
| 331 |
-
|
| 332 |
for i, path in enumerate(image_paths):
|
| 333 |
data = self.extract_landmarks(path)
|
| 334 |
if data is None:
|
| 335 |
return {'error': f'Failed to extract pose from image {i+1}'}
|
| 336 |
landmarks_list.append(data['landmarks'])
|
| 337 |
angle_lists.append(data['angles'])
|
| 338 |
-
|
| 339 |
similarity = self.compare_similarity(landmarks_list)
|
| 340 |
if similarity < 0.5:
|
| 341 |
return {'error': f'Images show different poses (similarity: {similarity:.2f})'}
|
| 342 |
-
|
| 343 |
angle_array = np.array(angle_lists)
|
| 344 |
avg_angles = np.mean(angle_array, axis=0).tolist()
|
| 345 |
tolerances = self.calculate_tolerances(angle_lists)
|
| 346 |
-
|
| 347 |
pose_id = pose_name.lower().replace(' ', '-').replace("'", "").replace('(', '').replace(')', '')
|
| 348 |
logger.info(f"π Average angles: {len(avg_angles)} angles, tolerances: {len(tolerances)}")
|
| 349 |
-
|
| 350 |
reference = {
|
| 351 |
'name': pose_name,
|
| 352 |
'difficulty': difficulty,
|
|
@@ -359,7 +380,7 @@ class PoseGenerator:
|
|
| 359 |
'similarity_score': similarity,
|
| 360 |
'is_custom': True
|
| 361 |
}
|
| 362 |
-
|
| 363 |
return {
|
| 364 |
'pose_id': pose_id,
|
| 365 |
'reference': reference,
|
|
@@ -367,7 +388,7 @@ class PoseGenerator:
|
|
| 367 |
'avg_angles': avg_angles,
|
| 368 |
'sample_count': len(image_paths)
|
| 369 |
}
|
| 370 |
-
|
| 371 |
def cleanup(self):
|
| 372 |
if hasattr(self, 'pose'):
|
| 373 |
self.pose.close()
|
|
@@ -375,22 +396,21 @@ class PoseGenerator:
|
|
| 375 |
|
| 376 |
class PoseReferenceLoader:
|
| 377 |
"""Load built-in poses from pose_reference.json."""
|
| 378 |
-
|
| 379 |
def __init__(self, reference_file=CONFIG['REFERENCE_FILE']):
|
| 380 |
self.reference_file = reference_file
|
| 381 |
self.pose_database = {}
|
| 382 |
self._load_reference()
|
| 383 |
-
|
| 384 |
def _load_reference(self):
|
| 385 |
if not os.path.exists(self.reference_file):
|
| 386 |
logger.warning(f"Reference file {self.reference_file} not found!")
|
| 387 |
self._generate_fallback()
|
| 388 |
return
|
| 389 |
-
|
| 390 |
try:
|
| 391 |
with open(self.reference_file, 'r') as f:
|
| 392 |
raw_data = json.load(f)
|
| 393 |
-
|
| 394 |
self.pose_database = {}
|
| 395 |
for key, data in raw_data.items():
|
| 396 |
normalized_id = key.lower().replace(' ', '-').replace("'", "").replace('(', '').replace(')', '')
|
|
@@ -398,12 +418,12 @@ class PoseReferenceLoader:
|
|
| 398 |
continue
|
| 399 |
data['name'] = key
|
| 400 |
self.pose_database[normalized_id] = data
|
| 401 |
-
|
| 402 |
logger.info(f"β
Loaded {len(self.pose_database)} built-in poses")
|
| 403 |
except Exception as e:
|
| 404 |
logger.error(f"Error loading {self.reference_file}: {e}")
|
| 405 |
self._generate_fallback()
|
| 406 |
-
|
| 407 |
def _generate_fallback(self):
|
| 408 |
fallback_data = {
|
| 409 |
'downward-dog': {
|
|
@@ -453,7 +473,7 @@ class PoseReferenceLoader:
|
|
| 453 |
}
|
| 454 |
self.pose_database = fallback_data
|
| 455 |
logger.info(f"Loaded {len(self.pose_database)} fallback poses")
|
| 456 |
-
|
| 457 |
def get_all_poses(self) -> List[Dict]:
|
| 458 |
result = []
|
| 459 |
for pose_id, data in self.pose_database.items():
|
|
@@ -467,10 +487,10 @@ class PoseReferenceLoader:
|
|
| 467 |
'is_custom': False,
|
| 468 |
})
|
| 469 |
return sorted(result, key=lambda x: x['name'])
|
| 470 |
-
|
| 471 |
def get_pose(self, pose_id: str) -> Optional[Dict]:
|
| 472 |
return self.pose_database.get(pose_id)
|
| 473 |
-
|
| 474 |
def merge_with_custom(self, custom_poses: Dict) -> Dict:
|
| 475 |
merged = self.pose_database.copy()
|
| 476 |
for pose_id, data in custom_poses.items():
|
|
@@ -481,7 +501,14 @@ class PoseReferenceLoader:
|
|
| 481 |
|
| 482 |
class PoseComparisonEngine:
|
| 483 |
"""Compare live pose with reference."""
|
| 484 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
def __init__(self):
|
| 486 |
self.joint_pairs = [
|
| 487 |
(11, 13, 15), (12, 14, 16), (11, 23, 25), (12, 24, 26),
|
|
@@ -489,7 +516,7 @@ class PoseComparisonEngine:
|
|
| 489 |
(11, 0, 12), (13, 11, 23), (14, 12, 24), (15, 13, 11),
|
| 490 |
(16, 14, 12), (25, 23, 24), (26, 24, 23),
|
| 491 |
]
|
| 492 |
-
|
| 493 |
def _calculate_angle(self, a, b, c):
|
| 494 |
a, b, c = np.array(a), np.array(b), np.array(c)
|
| 495 |
radians = np.arctan2(c[1] - b[1], c[0] - b[0]) - np.arctan2(a[1] - b[1], a[0] - b[0])
|
|
@@ -497,7 +524,7 @@ class PoseComparisonEngine:
|
|
| 497 |
if angle > 180:
|
| 498 |
angle = 360 - angle
|
| 499 |
return angle
|
| 500 |
-
|
| 501 |
def extract_angles(self, landmarks):
|
| 502 |
angles = []
|
| 503 |
try:
|
|
@@ -508,55 +535,67 @@ class PoseComparisonEngine:
|
|
| 508 |
except (IndexError, ValueError):
|
| 509 |
return None
|
| 510 |
return np.array(angles) if angles else None
|
| 511 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 512 |
def compare(self, current_angles, pose_id, merged_database=None) -> Tuple[float, List[str]]:
|
| 513 |
if merged_database is None:
|
| 514 |
return 0, []
|
| 515 |
-
|
| 516 |
reference_data = merged_database.get(pose_id)
|
| 517 |
if reference_data is None:
|
| 518 |
return 0, []
|
| 519 |
-
|
| 520 |
reference_angles = reference_data.get('angles', [])
|
| 521 |
tolerances = reference_data.get('tolerances', [])
|
| 522 |
weights = reference_data.get('weights', [])
|
| 523 |
-
|
|
|
|
| 524 |
if len(current_angles) == 0 or len(reference_angles) == 0:
|
| 525 |
return 0, []
|
| 526 |
-
|
| 527 |
min_len = min(len(current_angles), len(reference_angles))
|
| 528 |
current = current_angles[:min_len]
|
| 529 |
reference = reference_angles[:min_len]
|
| 530 |
tolerances = tolerances[:min_len] if tolerances else [15] * min_len
|
| 531 |
weights = weights[:min_len] if weights else [1.0] * min_len
|
| 532 |
-
|
| 533 |
differences = np.abs(current - reference)
|
| 534 |
-
|
| 535 |
joint_scores = []
|
| 536 |
joint_feedback = []
|
| 537 |
-
|
| 538 |
for i, diff in enumerate(differences):
|
| 539 |
tolerance = tolerances[i] if i < len(tolerances) else 15
|
| 540 |
weight = weights[i] if i < len(weights) else 1.0
|
| 541 |
-
|
| 542 |
if diff <= tolerance:
|
| 543 |
joint_score = 100
|
| 544 |
else:
|
| 545 |
excess = diff - tolerance
|
| 546 |
joint_score = max(0, 100 - (excess / 30) * 100)
|
| 547 |
-
|
|
|
|
|
|
|
|
|
|
| 548 |
joint_scores.append(joint_score * weight)
|
| 549 |
-
|
| 550 |
-
if diff > tolerance:
|
| 551 |
-
joint_feedback.append(f"Adjust joint {i+1}")
|
| 552 |
-
|
| 553 |
total_weight = sum(weights)
|
| 554 |
if total_weight > 0:
|
| 555 |
overall_score = sum(joint_scores) / total_weight
|
| 556 |
else:
|
| 557 |
overall_score = np.mean(joint_scores) if joint_scores else 0
|
| 558 |
-
|
| 559 |
-
# Cosine similarity
|
| 560 |
if np.linalg.norm(current) > 0 and np.linalg.norm(reference) > 0:
|
| 561 |
dot_product = np.dot(current, reference)
|
| 562 |
norm_current = np.linalg.norm(current)
|
|
@@ -565,10 +604,20 @@ class PoseComparisonEngine:
|
|
| 565 |
similarity_score = max(0, min(100, cosine_sim * 100))
|
| 566 |
else:
|
| 567 |
similarity_score = 0
|
| 568 |
-
|
| 569 |
final_score = 0.7 * overall_score + 0.3 * similarity_score
|
| 570 |
-
|
| 571 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 572 |
def get_status(self, score):
|
| 573 |
if score >= CONFIG['PERFECT_THRESHOLD']:
|
| 574 |
return 'π Excellent'
|
|
@@ -580,44 +629,30 @@ class PoseComparisonEngine:
|
|
| 580 |
return 'π Needs significant correction'
|
| 581 |
|
| 582 |
|
| 583 |
-
#
|
| 584 |
-
# Initialize Components
|
| 585 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 586 |
image_processor = ImageProcessor(CONFIG['TEMP_UPLOAD_DIR'])
|
| 587 |
custom_pose_manager = CustomPoseManager(CONFIG['USER_DATA_DIR'])
|
| 588 |
pose_generator = PoseGenerator()
|
| 589 |
reference_loader = PoseReferenceLoader(CONFIG['REFERENCE_FILE'])
|
| 590 |
comparison_engine = PoseComparisonEngine()
|
| 591 |
|
| 592 |
-
# Global cache for reference images
|
| 593 |
pose_reference_images = {}
|
| 594 |
|
| 595 |
-
|
| 596 |
def get_user_id() -> str:
|
| 597 |
-
"""
|
| 598 |
-
Get user ID from session (preferred) or from X-User-ID header (fallback).
|
| 599 |
-
"""
|
| 600 |
-
# 1. Check session (primary)
|
| 601 |
if 'user_id' in session:
|
| 602 |
return session['user_id']
|
| 603 |
-
# 2. Check header (for API clients)
|
| 604 |
user_id = request.headers.get('X-User-ID')
|
| 605 |
if user_id:
|
| 606 |
-
# Ensure user directory exists
|
| 607 |
user_dir = os.path.join(CONFIG['USER_DATA_DIR'], user_id)
|
| 608 |
if not os.path.exists(user_dir):
|
| 609 |
os.makedirs(user_dir, exist_ok=True)
|
| 610 |
return user_id
|
| 611 |
-
# 3. Fallback β should not happen after login
|
| 612 |
return 'anonymous'
|
| 613 |
|
| 614 |
-
|
| 615 |
def get_all_poses() -> List[Dict]:
|
| 616 |
-
"""Get all poses (built-in + custom) for the current user."""
|
| 617 |
user_id = get_user_id()
|
| 618 |
all_poses = reference_loader.get_all_poses()
|
| 619 |
-
|
| 620 |
-
# Load custom poses
|
| 621 |
custom_poses = custom_pose_manager.load_custom_poses(user_id)
|
| 622 |
for pose_id, data in custom_poses.items():
|
| 623 |
all_poses.append({
|
|
@@ -631,8 +666,7 @@ def get_all_poses() -> List[Dict]:
|
|
| 631 |
'generated_at': data.get('generated_at', None),
|
| 632 |
'similarity_score': data.get('similarity_score', None),
|
| 633 |
})
|
| 634 |
-
|
| 635 |
-
# Add emojis and default fields
|
| 636 |
emoji_map = {
|
| 637 |
'downward-dog': 'π', 'warrior-2': 'βοΈ', 'tree': 'π³',
|
| 638 |
'cobra': 'π', 'mountain': 'ποΈ', 'childs-pose': 'π',
|
|
@@ -647,20 +681,16 @@ def get_all_poses() -> List[Dict]:
|
|
| 647 |
pose['steps'] = ['Position yourself in the pose', 'Hold the posture', 'Breathe deeply']
|
| 648 |
if not pose.get('difficulty'):
|
| 649 |
pose['difficulty'] = 'Beginner'
|
| 650 |
-
|
| 651 |
-
return sorted(all_poses, key=lambda x: x['name'])
|
| 652 |
|
|
|
|
| 653 |
|
| 654 |
def get_merged_poses() -> Dict:
|
| 655 |
-
"""Get merged database for comparison."""
|
| 656 |
user_id = get_user_id()
|
| 657 |
custom_poses = custom_pose_manager.load_custom_poses(user_id)
|
| 658 |
return reference_loader.merge_with_custom(custom_poses)
|
| 659 |
|
| 660 |
|
| 661 |
-
#
|
| 662 |
-
# Authentication Routes
|
| 663 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 664 |
|
| 665 |
@app.route('/api/register', methods=['POST'])
|
| 666 |
def register():
|
|
@@ -712,15 +742,13 @@ def me():
|
|
| 712 |
return jsonify({'user_id': user_id, 'name': data['name']})
|
| 713 |
return jsonify({'error': 'User not found'}), 404
|
| 714 |
|
| 715 |
-
|
| 716 |
-
#
|
| 717 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 718 |
|
| 719 |
@app.route('/')
|
| 720 |
def index():
|
| 721 |
return render_template('index.html')
|
| 722 |
|
| 723 |
-
|
| 724 |
@app.route('/api/poses', methods=['GET'])
|
| 725 |
def get_poses():
|
| 726 |
try:
|
|
@@ -731,13 +759,13 @@ def get_poses():
|
|
| 731 |
logger.error(f"Error getting poses: {e}")
|
| 732 |
return jsonify([])
|
| 733 |
|
| 734 |
-
|
| 735 |
@app.route('/api/pose/<pose_id>/references', methods=['GET'])
|
| 736 |
def get_pose_references(pose_id):
|
| 737 |
user_id = get_user_id()
|
| 738 |
images = []
|
| 739 |
-
|
| 740 |
-
# Built
|
| 741 |
builtin_folder = os.path.join(CONFIG['YOGA_DIR'], pose_id)
|
| 742 |
if os.path.exists(builtin_folder):
|
| 743 |
for f in os.listdir(builtin_folder):
|
|
@@ -748,9 +776,22 @@ def get_pose_references(pose_id):
|
|
| 748 |
mime = 'image/jpeg' if f.endswith(('.jpg', '.jpeg')) else 'image/png'
|
| 749 |
images.append({'id': len(images), 'filename': f, 'data': img_data, 'mime': mime})
|
| 750 |
except Exception as e:
|
| 751 |
-
logger.error(f"Error loading reference image {f}: {e}")
|
| 752 |
-
|
| 753 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 754 |
custom_images = custom_pose_manager.get_custom_pose_images(user_id, pose_id)
|
| 755 |
for img_path in custom_images:
|
| 756 |
try:
|
|
@@ -759,23 +800,28 @@ def get_pose_references(pose_id):
|
|
| 759 |
images.append({'id': len(images), 'filename': os.path.basename(img_path), 'data': img_data, 'mime': 'image/jpeg'})
|
| 760 |
except Exception as e:
|
| 761 |
logger.error(f"Error loading custom reference image: {e}")
|
| 762 |
-
|
| 763 |
-
return jsonify({'references': images, 'count': len(images)})
|
| 764 |
|
|
|
|
| 765 |
|
|
|
|
| 766 |
@app.route('/api/live', methods=['POST'])
|
| 767 |
def api_live():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 768 |
start_time = time.time()
|
| 769 |
try:
|
| 770 |
data = request.get_json(silent=True)
|
| 771 |
if not data or 'image' not in data or 'pose_id' not in data:
|
| 772 |
return jsonify({'error': 'Missing image or pose_id'}), 400
|
| 773 |
-
|
| 774 |
pose_id = data['pose_id']
|
| 775 |
image_b64 = data['image']
|
| 776 |
if ',' in image_b64:
|
| 777 |
image_b64 = image_b64.split(',', 1)[1]
|
| 778 |
-
|
| 779 |
try:
|
| 780 |
img_bytes = base64.b64decode(image_b64)
|
| 781 |
nparr = np.frombuffer(img_bytes, np.uint8)
|
|
@@ -783,14 +829,14 @@ def api_live():
|
|
| 783 |
except Exception as e:
|
| 784 |
logger.error(f"Image decode error: {e}")
|
| 785 |
return jsonify({'error': 'Invalid image data'}), 400
|
| 786 |
-
|
| 787 |
if img is None:
|
| 788 |
return jsonify({'error': 'Could not decode image'}), 400
|
| 789 |
-
|
| 790 |
img = cv2.resize(img, CONFIG['IMAGE_SIZE'])
|
| 791 |
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 792 |
results = pose_live.process(rgb)
|
| 793 |
-
|
| 794 |
response_data = {
|
| 795 |
'score': 0,
|
| 796 |
'status': 'No person detected',
|
|
@@ -804,13 +850,13 @@ def api_live():
|
|
| 804 |
'processing_time': 0,
|
| 805 |
'landmarks': []
|
| 806 |
}
|
| 807 |
-
|
| 808 |
if results.pose_landmarks:
|
| 809 |
landmarks_data = [[lm.x, lm.y] for lm in results.pose_landmarks.landmark]
|
| 810 |
landmarks = np.array(landmarks_data)
|
| 811 |
-
|
| 812 |
merged_db = get_merged_poses()
|
| 813 |
-
|
| 814 |
if pose_id not in merged_db:
|
| 815 |
response_data['suggestions'] = [f'Pose "{pose_id}" not found', 'Try using Add Pose']
|
| 816 |
response_data['landmarks'] = landmarks_data
|
|
@@ -820,23 +866,22 @@ def api_live():
|
|
| 820 |
score, joint_feedback = comparison_engine.compare(current_angles, pose_id, merged_db)
|
| 821 |
score = int(round(score))
|
| 822 |
status = comparison_engine.get_status(score)
|
| 823 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 824 |
if score >= CONFIG['PERFECT_THRESHOLD']:
|
| 825 |
-
suggestions
|
| 826 |
-
suggestions.extend(joint_feedback[:2] if joint_feedback else ['Focus on deep breathing'])
|
| 827 |
elif score >= CONFIG['GOOD_THRESHOLD']:
|
| 828 |
-
suggestions
|
| 829 |
-
suggestions.extend(joint_feedback[:3])
|
| 830 |
else:
|
| 831 |
-
suggestions
|
| 832 |
-
|
| 833 |
-
if len(joint_feedback) < 2:
|
| 834 |
-
suggestions.append('Practice the basic pose first')
|
| 835 |
-
|
| 836 |
color = (34, 197, 94) if score >= 80 else (245, 158, 11) if score >= 65 else (239, 68, 68)
|
| 837 |
drawing_spec = mp_drawing.DrawingSpec(color=color, thickness=2, circle_radius=3)
|
| 838 |
mp_drawing.draw_landmarks(img, results.pose_landmarks, mp_pose.POSE_CONNECTIONS, drawing_spec, drawing_spec)
|
| 839 |
-
|
| 840 |
response_data = {
|
| 841 |
'score': score,
|
| 842 |
'status': status,
|
|
@@ -855,17 +900,18 @@ def api_live():
|
|
| 855 |
'Stand back so camera captures head to feet',
|
| 856 |
'Ensure good lighting'
|
| 857 |
]
|
| 858 |
-
|
| 859 |
_, buffer = cv2.imencode('.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, CONFIG['JPEG_QUALITY']])
|
| 860 |
response_data['image'] = base64.b64encode(buffer).decode('utf-8')
|
| 861 |
response_data['processing_time'] = int((time.time() - start_time) * 1000)
|
| 862 |
-
|
| 863 |
return jsonify(response_data)
|
| 864 |
-
|
| 865 |
except Exception as e:
|
| 866 |
logger.error(f"API Live error: {e}", exc_info=True)
|
| 867 |
return jsonify({'error': str(e), 'score': 0, 'status': 'Error', 'suggestions': ['An error occurred'], 'landmarks': []}), 500
|
| 868 |
|
|
|
|
| 869 |
|
| 870 |
@app.route('/api/generate-pose', methods=['POST'])
|
| 871 |
def generate_pose():
|
|
@@ -874,118 +920,114 @@ def generate_pose():
|
|
| 874 |
name = request.form.get('name', '').strip()
|
| 875 |
if not name:
|
| 876 |
return jsonify({'error': 'Pose name is required'}), 400
|
| 877 |
-
|
| 878 |
category = request.form.get('category', 'General')
|
| 879 |
difficulty = request.form.get('difficulty', 'Beginner')
|
| 880 |
-
|
| 881 |
image_paths = []
|
| 882 |
for i in range(5):
|
| 883 |
file_key = f'image_{i}'
|
| 884 |
if file_key not in request.files:
|
| 885 |
logger.error(f"Missing image {i+1}")
|
| 886 |
return jsonify({'error': f'Missing image {i+1}'}), 400
|
| 887 |
-
|
| 888 |
file = request.files[file_key]
|
| 889 |
if file.filename == '':
|
| 890 |
logger.error(f"Empty file for image {i+1}")
|
| 891 |
return jsonify({'error': f'Empty file for image {i+1}'}), 400
|
| 892 |
-
|
| 893 |
logger.info(f"π₯ Received image {i+1}: {file.filename}")
|
| 894 |
temp_path = image_processor.save_temp_image(file.read(), file.filename)
|
| 895 |
if not temp_path:
|
| 896 |
logger.error(f"Failed to save image {i+1}")
|
| 897 |
return jsonify({'error': f'Failed to save image {i+1}'}), 400
|
| 898 |
-
|
| 899 |
image_paths.append(temp_path)
|
| 900 |
logger.info(f"β
Saved to: {temp_path}")
|
| 901 |
-
|
| 902 |
result = pose_generator.generate_pose_reference(
|
| 903 |
image_paths=image_paths,
|
| 904 |
pose_name=name,
|
| 905 |
difficulty=difficulty,
|
| 906 |
category=category
|
| 907 |
)
|
| 908 |
-
|
| 909 |
for path in image_paths:
|
| 910 |
image_processor.delete_temp_file(path)
|
| 911 |
-
|
| 912 |
if result is None:
|
| 913 |
logger.error("Generation result is None")
|
| 914 |
return jsonify({'error': 'Failed to generate pose'}), 400
|
| 915 |
-
|
| 916 |
if 'error' in result:
|
| 917 |
logger.error(f"Generation error: {result['error']}")
|
| 918 |
return jsonify({'error': result['error']}), 400
|
| 919 |
-
|
| 920 |
result['pose_name'] = name
|
| 921 |
result['category'] = category
|
| 922 |
result['difficulty'] = difficulty
|
| 923 |
-
|
| 924 |
logger.info(f"β
Pose generated successfully: {name}")
|
| 925 |
return jsonify(result)
|
| 926 |
-
|
| 927 |
except Exception as e:
|
| 928 |
logger.error(f"Error generating pose: {e}", exc_info=True)
|
| 929 |
return jsonify({'error': str(e)}), 500
|
| 930 |
|
| 931 |
-
|
| 932 |
@app.route('/api/save-custom-pose', methods=['POST'])
|
| 933 |
def save_custom_pose():
|
| 934 |
try:
|
| 935 |
data = request.get_json()
|
| 936 |
if not data:
|
| 937 |
return jsonify({'error': 'No data provided'}), 400
|
| 938 |
-
|
| 939 |
pose_id = data.get('pose_id')
|
| 940 |
reference = data.get('reference')
|
| 941 |
name = data.get('name', pose_id)
|
| 942 |
-
|
| 943 |
if not pose_id or not reference:
|
| 944 |
return jsonify({'error': 'Missing pose_id or reference'}), 400
|
| 945 |
-
|
| 946 |
if 'angles' not in reference:
|
| 947 |
return jsonify({'error': 'Invalid reference: missing "angles"'}), 400
|
| 948 |
-
|
| 949 |
user_id = get_user_id()
|
| 950 |
logger.info(f"πΎ Saving custom pose '{name}' (ID: {pose_id}) for user {user_id[:8]}")
|
| 951 |
-
|
| 952 |
success = custom_pose_manager.add_custom_pose(
|
| 953 |
user_id=user_id,
|
| 954 |
pose_id=pose_id,
|
| 955 |
reference=reference,
|
| 956 |
images=[]
|
| 957 |
)
|
| 958 |
-
|
| 959 |
if not success:
|
| 960 |
logger.error("Failed to save custom pose")
|
| 961 |
return jsonify({'error': 'Failed to save pose'}), 500
|
| 962 |
-
|
| 963 |
-
# Invalidate cache
|
| 964 |
global pose_reference_images
|
| 965 |
cache_key = f"{user_id}_{pose_id}"
|
| 966 |
if cache_key in pose_reference_images:
|
| 967 |
del pose_reference_images[cache_key]
|
| 968 |
logger.info(f"ποΈ Invalidated cache for {cache_key}")
|
| 969 |
-
|
| 970 |
logger.info(f"β
Pose '{name}' saved successfully")
|
| 971 |
return jsonify({
|
| 972 |
'success': True,
|
| 973 |
'message': f'Pose "{name}" saved successfully',
|
| 974 |
'pose_id': pose_id
|
| 975 |
})
|
| 976 |
-
|
| 977 |
except Exception as e:
|
| 978 |
logger.error(f"Error saving custom pose: {e}", exc_info=True)
|
| 979 |
return jsonify({'error': str(e)}), 500
|
| 980 |
|
| 981 |
-
|
| 982 |
@app.route('/api/custom-poses', methods=['GET'])
|
| 983 |
def get_custom_poses():
|
| 984 |
user_id = get_user_id()
|
| 985 |
poses = custom_pose_manager.load_custom_poses(user_id)
|
| 986 |
return jsonify(poses)
|
| 987 |
|
| 988 |
-
|
| 989 |
@app.route('/api/health', methods=['GET'])
|
| 990 |
def health_check():
|
| 991 |
user_id = get_user_id()
|
|
@@ -996,19 +1038,16 @@ def health_check():
|
|
| 996 |
'custom_poses': len(custom_pose_manager.load_custom_poses(user_id)),
|
| 997 |
})
|
| 998 |
|
|
|
|
| 999 |
|
| 1000 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1001 |
-
# Main Entry Point
|
| 1002 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1003 |
if __name__ == '__main__':
|
| 1004 |
logger.info("=" * 60)
|
| 1005 |
logger.info("π§ YogaMate Server Starting...")
|
| 1006 |
logger.info(f"π Built-in poses: {len(reference_loader.pose_database)}")
|
| 1007 |
logger.info("=" * 60)
|
| 1008 |
-
|
| 1009 |
-
# Cleanup temp directory
|
| 1010 |
image_processor.cleanup_temp_dir()
|
| 1011 |
-
|
| 1012 |
app.run(
|
| 1013 |
host='0.0.0.0',
|
| 1014 |
port=7860,
|
|
|
|
| 12 |
import shutil
|
| 13 |
from datetime import datetime
|
| 14 |
from typing import Dict, List, Optional, Tuple, Any
|
| 15 |
+
from logging.handlers import RotatingFileHandler
|
| 16 |
|
| 17 |
import numpy as np
|
| 18 |
import cv2
|
|
|
|
| 22 |
from flask_compress import Compress
|
| 23 |
from werkzeug.security import generate_password_hash, check_password_hash
|
| 24 |
|
| 25 |
+
# βββ Logging Setup ββββββββββββββββββββββββββββββββββββββββββββ
|
| 26 |
+
log_formatter = logging.Formatter(
|
| 27 |
+
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 28 |
+
)
|
| 29 |
+
console_handler = logging.StreamHandler()
|
| 30 |
+
console_handler.setFormatter(log_formatter)
|
| 31 |
+
|
| 32 |
+
file_handler = RotatingFileHandler(
|
| 33 |
+
'yogamate.log', maxBytes=10*1024*1024, backupCount=3
|
| 34 |
+
)
|
| 35 |
+
file_handler.setFormatter(log_formatter)
|
| 36 |
+
|
| 37 |
logger = logging.getLogger(__name__)
|
| 38 |
+
logger.setLevel(logging.INFO)
|
| 39 |
+
logger.addHandler(console_handler)
|
| 40 |
+
logger.addHandler(file_handler)
|
| 41 |
|
| 42 |
+
# βββ Flask App βββββββββββββββββββββββββββββββββββββββββββββ
|
| 43 |
app = Flask(__name__)
|
| 44 |
app.secret_key = os.environ.get('SECRET_KEY', 'yogamate-secret-key-change-in-production')
|
| 45 |
CORS(app, supports_credentials=True)
|
| 46 |
Compress(app)
|
| 47 |
|
| 48 |
+
# βββ Configuration from Environment ββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
CONFIG = {
|
| 50 |
'IMAGE_SIZE': (256, 192),
|
| 51 |
'JPEG_QUALITY': 50,
|
| 52 |
+
'MIN_DETECTION_CONFIDENCE': float(os.environ.get('MIN_DETECTION_CONFIDENCE', 0.5)),
|
| 53 |
+
'MIN_TRACKING_CONFIDENCE': float(os.environ.get('MIN_TRACKING_CONFIDENCE', 0.3)),
|
| 54 |
+
'MODEL_COMPLEXITY': int(os.environ.get('MODEL_COMPLEXITY', 0)),
|
| 55 |
+
'SMOOTH_LANDMARKS': bool(os.environ.get('SMOOTH_LANDMARKS', '1') == '1'),
|
| 56 |
+
'REFERENCE_FILE': os.environ.get('REFERENCE_FILE', 'pose_reference.json'),
|
| 57 |
+
'PERFECT_THRESHOLD': int(os.environ.get('PERFECT_THRESHOLD', 80)),
|
| 58 |
+
'GOOD_THRESHOLD': int(os.environ.get('GOOD_THRESHOLD', 65)),
|
| 59 |
+
'USER_DATA_DIR': os.environ.get('USER_DATA_DIR', 'user_data'),
|
| 60 |
+
'TEMP_UPLOAD_DIR': os.environ.get('TEMP_UPLOAD_DIR', 'temp_uploads'),
|
| 61 |
+
'YOGA_DIR': os.environ.get('YOGA_DIR', 'yoga'),
|
| 62 |
+
# NEW: directory for extracted reference images
|
| 63 |
+
'REFERENCE_IMAGES_DIR': os.environ.get('REFERENCE_IMAGES_DIR', 'reference_images'),
|
| 64 |
}
|
| 65 |
|
| 66 |
+
# βββ User Store βββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
| 67 |
USER_STORE = 'users.json'
|
| 68 |
|
| 69 |
def load_users():
|
|
|
|
| 76 |
with open(USER_STORE, 'w') as f:
|
| 77 |
json.dump(users, f, indent=2)
|
| 78 |
|
| 79 |
+
# βββ MediaPipe Setup ββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
| 80 |
mp_pose = mp.solutions.pose
|
| 81 |
mp_drawing = mp.solutions.drawing_utils
|
| 82 |
|
|
|
|
| 90 |
smooth_segmentation=False
|
| 91 |
)
|
| 92 |
|
| 93 |
+
# βββ Rate Limiter ββββββββββββββββββββββββββββββββββββββββββ
|
| 94 |
+
class RateLimiter:
|
| 95 |
+
def __init__(self, max_requests=10, per_seconds=1):
|
| 96 |
+
self.max_requests = max_requests
|
| 97 |
+
self.per_seconds = per_seconds
|
| 98 |
+
self.requests = {}
|
| 99 |
+
|
| 100 |
+
def is_allowed(self, key):
|
| 101 |
+
now = time.time()
|
| 102 |
+
timestamps = self.requests.get(key, [])
|
| 103 |
+
timestamps = [t for t in timestamps if now - t < self.per_seconds]
|
| 104 |
+
if len(timestamps) >= self.max_requests:
|
| 105 |
+
return False
|
| 106 |
+
timestamps.append(now)
|
| 107 |
+
self.requests[key] = timestamps
|
| 108 |
+
return True
|
| 109 |
+
|
| 110 |
+
rate_limiter = RateLimiter(max_requests=10, per_seconds=1)
|
| 111 |
+
|
| 112 |
+
# βββ Helper Classes ββββββββββββββββββββββββββββββββββββββββββ
|
| 113 |
|
| 114 |
class ImageProcessor:
|
| 115 |
"""Handle image processing and validation."""
|
|
|
|
| 116 |
ALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.webp'}
|
| 117 |
MAX_FILE_SIZE = 10 * 1024 * 1024
|
| 118 |
REQUIRED_IMAGES = 5
|
| 119 |
+
|
| 120 |
def __init__(self, upload_dir: str = "temp_uploads"):
|
| 121 |
self.upload_dir = upload_dir
|
| 122 |
os.makedirs(upload_dir, exist_ok=True)
|
| 123 |
+
|
| 124 |
def save_temp_image(self, file_data: bytes, original_filename: str) -> Optional[str]:
|
| 125 |
logger.info(f"π₯ Saving temp image: {original_filename}")
|
| 126 |
try:
|
|
|
|
| 128 |
if ext not in self.ALLOWED_EXTENSIONS:
|
| 129 |
ext = 'jpg'
|
| 130 |
logger.info(f"π Extension changed to {ext}")
|
| 131 |
+
|
| 132 |
filename = f"{uuid.uuid4()}.{ext}"
|
| 133 |
file_path = os.path.join(self.upload_dir, filename)
|
| 134 |
+
|
| 135 |
with open(file_path, 'wb') as f:
|
| 136 |
f.write(file_data)
|
| 137 |
logger.info(f"πΎ File written to {file_path} ({len(file_data)} bytes)")
|
| 138 |
+
|
|
|
|
| 139 |
try:
|
| 140 |
import PIL.Image
|
| 141 |
img = PIL.Image.open(file_path)
|
|
|
|
| 146 |
os.remove(file_path)
|
| 147 |
logger.error(f"β Image validation failed: {e}")
|
| 148 |
return None
|
| 149 |
+
|
| 150 |
except Exception as e:
|
| 151 |
logger.error(f"β Error saving temp image: {e}")
|
| 152 |
return None
|
| 153 |
+
|
| 154 |
def delete_temp_file(self, file_path: str) -> bool:
|
| 155 |
try:
|
| 156 |
if os.path.exists(file_path):
|
|
|
|
| 160 |
except Exception as e:
|
| 161 |
logger.error(f"Error deleting temp file: {e}")
|
| 162 |
return False
|
| 163 |
+
|
| 164 |
def cleanup_temp_dir(self):
|
| 165 |
import time
|
| 166 |
now = time.time()
|
|
|
|
| 177 |
|
| 178 |
class CustomPoseManager:
|
| 179 |
"""Manage user-specific custom poses."""
|
|
|
|
| 180 |
def __init__(self, base_dir: str = "user_data"):
|
| 181 |
self.base_dir = base_dir
|
| 182 |
os.makedirs(self.base_dir, exist_ok=True)
|
| 183 |
+
|
| 184 |
def get_user_dir(self, user_id: str) -> str:
|
| 185 |
return os.path.join(self.base_dir, user_id)
|
| 186 |
+
|
| 187 |
def get_custom_poses_path(self, user_id: str) -> str:
|
| 188 |
return os.path.join(self.get_user_dir(user_id), "custom_poses.json")
|
| 189 |
+
|
| 190 |
def get_upload_dir(self, user_id: str, pose_id: str) -> str:
|
| 191 |
path = os.path.join(self.get_user_dir(user_id), "images", pose_id)
|
| 192 |
os.makedirs(path, exist_ok=True)
|
| 193 |
return path
|
| 194 |
+
|
| 195 |
def load_custom_poses(self, user_id: str) -> Dict:
|
| 196 |
path = self.get_custom_poses_path(user_id)
|
| 197 |
if os.path.exists(path):
|
|
|
|
| 203 |
except Exception as e:
|
| 204 |
logger.error(f"Error loading custom poses: {e}")
|
| 205 |
return {}
|
| 206 |
+
|
| 207 |
def save_custom_poses(self, user_id: str, poses: Dict) -> bool:
|
| 208 |
path = self.get_custom_poses_path(user_id)
|
| 209 |
try:
|
|
|
|
| 215 |
except Exception as e:
|
| 216 |
logger.error(f"Error saving custom poses: {e}")
|
| 217 |
return False
|
| 218 |
+
|
| 219 |
def add_custom_pose(self, user_id: str, pose_id: str, reference: Dict, images: List[str]) -> bool:
|
| 220 |
logger.info(f"π Adding custom pose {pose_id} for user {user_id[:8]}")
|
| 221 |
poses = self.load_custom_poses(user_id)
|
| 222 |
+
|
| 223 |
if pose_id in poses:
|
| 224 |
logger.warning(f"β οΈ Pose {pose_id} already exists, overwriting")
|
| 225 |
+
|
| 226 |
poses[pose_id] = reference
|
| 227 |
logger.info(f"π Reference data for {pose_id}: angles={len(reference.get('angles', []))} joints")
|
| 228 |
+
|
| 229 |
if images:
|
| 230 |
upload_dir = self.get_upload_dir(user_id, pose_id)
|
| 231 |
logger.info(f"π Saving {len(images)} images to {upload_dir}")
|
|
|
|
| 238 |
logger.warning(f"β οΈ Image {img_path} not found, skipping")
|
| 239 |
else:
|
| 240 |
logger.info("βΉοΈ No images to copy (they are deleted after processing)")
|
| 241 |
+
|
| 242 |
success = self.save_custom_poses(user_id, poses)
|
| 243 |
if success:
|
| 244 |
logger.info(f"β
Custom poses saved (total: {len(poses)})")
|
| 245 |
else:
|
| 246 |
logger.error("β Failed to save custom poses")
|
| 247 |
return success
|
| 248 |
+
|
| 249 |
def get_custom_pose_images(self, user_id: str, pose_id: str) -> List[str]:
|
| 250 |
upload_dir = self.get_upload_dir(user_id, pose_id)
|
| 251 |
if not os.path.exists(upload_dir):
|
| 252 |
return []
|
| 253 |
+
|
| 254 |
images = []
|
| 255 |
for f in sorted(os.listdir(upload_dir)):
|
| 256 |
if f.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')):
|
|
|
|
| 260 |
|
| 261 |
class PoseGenerator:
|
| 262 |
"""Generate pose references from images."""
|
|
|
|
| 263 |
def __init__(self):
|
| 264 |
self.pose = mp_pose.Pose(
|
| 265 |
static_image_mode=True,
|
|
|
|
| 272 |
(11, 0, 12), (13, 11, 23), (14, 12, 24), (15, 13, 11),
|
| 273 |
(16, 14, 12), (25, 23, 24), (26, 24, 23),
|
| 274 |
]
|
| 275 |
+
self.default_weights = [1.0, 1.0, 1.2, 1.2, 1.0, 1.0, 0.8, 0.8,
|
| 276 |
0.8, 1.0, 1.0, 0.7, 0.7, 0.8, 0.8]
|
| 277 |
+
|
| 278 |
def _calculate_angle(self, a, b, c):
|
| 279 |
a, b, c = np.array(a), np.array(b), np.array(c)
|
| 280 |
radians = np.arctan2(c[1] - b[1], c[0] - b[0]) - np.arctan2(a[1] - b[1], a[0] - b[0])
|
|
|
|
| 282 |
if angle > 180:
|
| 283 |
angle = 360 - angle
|
| 284 |
return angle
|
| 285 |
+
|
| 286 |
def extract_landmarks(self, image_path: str) -> Optional[Dict]:
|
| 287 |
logger.info(f"π Extracting landmarks from {image_path}")
|
| 288 |
try:
|
|
|
|
| 290 |
if img is None:
|
| 291 |
logger.error(f"β Could not read image: {image_path}")
|
| 292 |
return None
|
| 293 |
+
|
| 294 |
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 295 |
results = self.pose.process(rgb)
|
| 296 |
+
|
| 297 |
if not results.pose_landmarks:
|
| 298 |
logger.warning(f"β οΈ No pose detected in {image_path}")
|
| 299 |
return None
|
| 300 |
+
|
| 301 |
landmarks = [[lm.x, lm.y] for lm in results.pose_landmarks.landmark]
|
| 302 |
logger.info(f"β
Detected {len(landmarks)} landmarks")
|
| 303 |
+
|
| 304 |
angles = []
|
| 305 |
for a, b, c in self.joint_pairs:
|
| 306 |
if a >= len(landmarks) or b >= len(landmarks) or c >= len(landmarks):
|
| 307 |
logger.warning(f"β οΈ Landmark index out of range for {a},{b},{c}")
|
| 308 |
return None
|
| 309 |
angles.append(self._calculate_angle(landmarks[a], landmarks[b], landmarks[c]))
|
| 310 |
+
|
| 311 |
logger.info(f"β
Extracted {len(angles)} angles")
|
| 312 |
return {
|
| 313 |
'landmarks': landmarks,
|
| 314 |
'angles': angles,
|
| 315 |
'confidence': results.pose_landmarks.landmark[0].visibility
|
| 316 |
}
|
| 317 |
+
|
| 318 |
except Exception as e:
|
| 319 |
logger.error(f"β Error extracting landmarks: {e}")
|
| 320 |
return None
|
| 321 |
+
|
| 322 |
def calculate_tolerances(self, angle_lists: List[List[float]]) -> List[float]:
|
| 323 |
angle_array = np.array(angle_lists)
|
| 324 |
std_devs = np.std(angle_array, axis=0)
|
| 325 |
return [max(5, min(25, std * 2)) for std in std_devs]
|
| 326 |
+
|
| 327 |
def compare_similarity(self, landmarks_list: List[List[List[float]]]) -> float:
|
| 328 |
if len(landmarks_list) < 2:
|
| 329 |
return 1.0
|
| 330 |
+
|
| 331 |
arrays = [np.array(lm) for lm in landmarks_list]
|
| 332 |
similarities = []
|
| 333 |
+
|
| 334 |
for i in range(len(arrays)):
|
| 335 |
for j in range(i + 1, len(arrays)):
|
| 336 |
if arrays[i].shape != arrays[j].shape:
|
|
|
|
| 338 |
diff = np.mean((arrays[i] - arrays[j]) ** 2)
|
| 339 |
sim = max(0, 1 - (diff * 5))
|
| 340 |
similarities.append(sim)
|
| 341 |
+
|
| 342 |
return float(np.mean(similarities)) if similarities else 0.0
|
| 343 |
+
|
| 344 |
def generate_pose_reference(self, image_paths: List[str], pose_name: str,
|
| 345 |
difficulty: str = "Beginner", category: str = "General") -> Optional[Dict]:
|
| 346 |
logger.info(f"π Generating reference for '{pose_name}' with {len(image_paths)} images")
|
| 347 |
if len(image_paths) != 5:
|
| 348 |
return {'error': f'Expected 5 images, got {len(image_paths)}'}
|
| 349 |
+
|
| 350 |
landmarks_list = []
|
| 351 |
angle_lists = []
|
| 352 |
+
|
| 353 |
for i, path in enumerate(image_paths):
|
| 354 |
data = self.extract_landmarks(path)
|
| 355 |
if data is None:
|
| 356 |
return {'error': f'Failed to extract pose from image {i+1}'}
|
| 357 |
landmarks_list.append(data['landmarks'])
|
| 358 |
angle_lists.append(data['angles'])
|
| 359 |
+
|
| 360 |
similarity = self.compare_similarity(landmarks_list)
|
| 361 |
if similarity < 0.5:
|
| 362 |
return {'error': f'Images show different poses (similarity: {similarity:.2f})'}
|
| 363 |
+
|
| 364 |
angle_array = np.array(angle_lists)
|
| 365 |
avg_angles = np.mean(angle_array, axis=0).tolist()
|
| 366 |
tolerances = self.calculate_tolerances(angle_lists)
|
| 367 |
+
|
| 368 |
pose_id = pose_name.lower().replace(' ', '-').replace("'", "").replace('(', '').replace(')', '')
|
| 369 |
logger.info(f"π Average angles: {len(avg_angles)} angles, tolerances: {len(tolerances)}")
|
| 370 |
+
|
| 371 |
reference = {
|
| 372 |
'name': pose_name,
|
| 373 |
'difficulty': difficulty,
|
|
|
|
| 380 |
'similarity_score': similarity,
|
| 381 |
'is_custom': True
|
| 382 |
}
|
| 383 |
+
|
| 384 |
return {
|
| 385 |
'pose_id': pose_id,
|
| 386 |
'reference': reference,
|
|
|
|
| 388 |
'avg_angles': avg_angles,
|
| 389 |
'sample_count': len(image_paths)
|
| 390 |
}
|
| 391 |
+
|
| 392 |
def cleanup(self):
|
| 393 |
if hasattr(self, 'pose'):
|
| 394 |
self.pose.close()
|
|
|
|
| 396 |
|
| 397 |
class PoseReferenceLoader:
|
| 398 |
"""Load built-in poses from pose_reference.json."""
|
|
|
|
| 399 |
def __init__(self, reference_file=CONFIG['REFERENCE_FILE']):
|
| 400 |
self.reference_file = reference_file
|
| 401 |
self.pose_database = {}
|
| 402 |
self._load_reference()
|
| 403 |
+
|
| 404 |
def _load_reference(self):
|
| 405 |
if not os.path.exists(self.reference_file):
|
| 406 |
logger.warning(f"Reference file {self.reference_file} not found!")
|
| 407 |
self._generate_fallback()
|
| 408 |
return
|
| 409 |
+
|
| 410 |
try:
|
| 411 |
with open(self.reference_file, 'r') as f:
|
| 412 |
raw_data = json.load(f)
|
| 413 |
+
|
| 414 |
self.pose_database = {}
|
| 415 |
for key, data in raw_data.items():
|
| 416 |
normalized_id = key.lower().replace(' ', '-').replace("'", "").replace('(', '').replace(')', '')
|
|
|
|
| 418 |
continue
|
| 419 |
data['name'] = key
|
| 420 |
self.pose_database[normalized_id] = data
|
| 421 |
+
|
| 422 |
logger.info(f"β
Loaded {len(self.pose_database)} built-in poses")
|
| 423 |
except Exception as e:
|
| 424 |
logger.error(f"Error loading {self.reference_file}: {e}")
|
| 425 |
self._generate_fallback()
|
| 426 |
+
|
| 427 |
def _generate_fallback(self):
|
| 428 |
fallback_data = {
|
| 429 |
'downward-dog': {
|
|
|
|
| 473 |
}
|
| 474 |
self.pose_database = fallback_data
|
| 475 |
logger.info(f"Loaded {len(self.pose_database)} fallback poses")
|
| 476 |
+
|
| 477 |
def get_all_poses(self) -> List[Dict]:
|
| 478 |
result = []
|
| 479 |
for pose_id, data in self.pose_database.items():
|
|
|
|
| 487 |
'is_custom': False,
|
| 488 |
})
|
| 489 |
return sorted(result, key=lambda x: x['name'])
|
| 490 |
+
|
| 491 |
def get_pose(self, pose_id: str) -> Optional[Dict]:
|
| 492 |
return self.pose_database.get(pose_id)
|
| 493 |
+
|
| 494 |
def merge_with_custom(self, custom_poses: Dict) -> Dict:
|
| 495 |
merged = self.pose_database.copy()
|
| 496 |
for pose_id, data in custom_poses.items():
|
|
|
|
| 501 |
|
| 502 |
class PoseComparisonEngine:
|
| 503 |
"""Compare live pose with reference."""
|
| 504 |
+
|
| 505 |
+
FEEDBACK_KEYS = [
|
| 506 |
+
'left_elbow', 'right_elbow', 'left_hip', 'right_hip',
|
| 507 |
+
'left_knee', 'right_knee', 'torso_left', 'torso_right',
|
| 508 |
+
'neck', 'left_shoulder', 'right_shoulder',
|
| 509 |
+
'left_arm', 'right_arm', 'left_leg', 'right_leg'
|
| 510 |
+
]
|
| 511 |
+
|
| 512 |
def __init__(self):
|
| 513 |
self.joint_pairs = [
|
| 514 |
(11, 13, 15), (12, 14, 16), (11, 23, 25), (12, 24, 26),
|
|
|
|
| 516 |
(11, 0, 12), (13, 11, 23), (14, 12, 24), (15, 13, 11),
|
| 517 |
(16, 14, 12), (25, 23, 24), (26, 24, 23),
|
| 518 |
]
|
| 519 |
+
|
| 520 |
def _calculate_angle(self, a, b, c):
|
| 521 |
a, b, c = np.array(a), np.array(b), np.array(c)
|
| 522 |
radians = np.arctan2(c[1] - b[1], c[0] - b[0]) - np.arctan2(a[1] - b[1], a[0] - b[0])
|
|
|
|
| 524 |
if angle > 180:
|
| 525 |
angle = 360 - angle
|
| 526 |
return angle
|
| 527 |
+
|
| 528 |
def extract_angles(self, landmarks):
|
| 529 |
angles = []
|
| 530 |
try:
|
|
|
|
| 535 |
except (IndexError, ValueError):
|
| 536 |
return None
|
| 537 |
return np.array(angles) if angles else None
|
| 538 |
+
|
| 539 |
+
def _get_feedback_message(self, idx, diff, feedback_dict):
|
| 540 |
+
if idx >= len(self.FEEDBACK_KEYS):
|
| 541 |
+
return f"Adjust joint {idx+1}"
|
| 542 |
+
key = self.FEEDBACK_KEYS[idx]
|
| 543 |
+
if feedback_dict and key in feedback_dict:
|
| 544 |
+
if diff > 0:
|
| 545 |
+
msg = feedback_dict[key].get('high', f"Lower your {key.replace('_', ' ')}")
|
| 546 |
+
else:
|
| 547 |
+
msg = feedback_dict[key].get('low', f"Raise your {key.replace('_', ' ')}")
|
| 548 |
+
return msg
|
| 549 |
+
return f"Adjust your {key.replace('_', ' ')}"
|
| 550 |
+
|
| 551 |
def compare(self, current_angles, pose_id, merged_database=None) -> Tuple[float, List[str]]:
|
| 552 |
if merged_database is None:
|
| 553 |
return 0, []
|
| 554 |
+
|
| 555 |
reference_data = merged_database.get(pose_id)
|
| 556 |
if reference_data is None:
|
| 557 |
return 0, []
|
| 558 |
+
|
| 559 |
reference_angles = reference_data.get('angles', [])
|
| 560 |
tolerances = reference_data.get('tolerances', [])
|
| 561 |
weights = reference_data.get('weights', [])
|
| 562 |
+
feedback_dict = reference_data.get('feedback', {})
|
| 563 |
+
|
| 564 |
if len(current_angles) == 0 or len(reference_angles) == 0:
|
| 565 |
return 0, []
|
| 566 |
+
|
| 567 |
min_len = min(len(current_angles), len(reference_angles))
|
| 568 |
current = current_angles[:min_len]
|
| 569 |
reference = reference_angles[:min_len]
|
| 570 |
tolerances = tolerances[:min_len] if tolerances else [15] * min_len
|
| 571 |
weights = weights[:min_len] if weights else [1.0] * min_len
|
| 572 |
+
|
| 573 |
differences = np.abs(current - reference)
|
| 574 |
+
|
| 575 |
joint_scores = []
|
| 576 |
joint_feedback = []
|
| 577 |
+
|
| 578 |
for i, diff in enumerate(differences):
|
| 579 |
tolerance = tolerances[i] if i < len(tolerances) else 15
|
| 580 |
weight = weights[i] if i < len(weights) else 1.0
|
| 581 |
+
|
| 582 |
if diff <= tolerance:
|
| 583 |
joint_score = 100
|
| 584 |
else:
|
| 585 |
excess = diff - tolerance
|
| 586 |
joint_score = max(0, 100 - (excess / 30) * 100)
|
| 587 |
+
angle_diff = current[i] - reference[i]
|
| 588 |
+
msg = self._get_feedback_message(i, angle_diff, feedback_dict)
|
| 589 |
+
joint_feedback.append(msg)
|
| 590 |
+
|
| 591 |
joint_scores.append(joint_score * weight)
|
| 592 |
+
|
|
|
|
|
|
|
|
|
|
| 593 |
total_weight = sum(weights)
|
| 594 |
if total_weight > 0:
|
| 595 |
overall_score = sum(joint_scores) / total_weight
|
| 596 |
else:
|
| 597 |
overall_score = np.mean(joint_scores) if joint_scores else 0
|
| 598 |
+
|
|
|
|
| 599 |
if np.linalg.norm(current) > 0 and np.linalg.norm(reference) > 0:
|
| 600 |
dot_product = np.dot(current, reference)
|
| 601 |
norm_current = np.linalg.norm(current)
|
|
|
|
| 604 |
similarity_score = max(0, min(100, cosine_sim * 100))
|
| 605 |
else:
|
| 606 |
similarity_score = 0
|
| 607 |
+
|
| 608 |
final_score = 0.7 * overall_score + 0.3 * similarity_score
|
| 609 |
+
final_score = max(0, min(100, final_score))
|
| 610 |
+
|
| 611 |
+
if not joint_feedback:
|
| 612 |
+
if final_score >= CONFIG['PERFECT_THRESHOLD']:
|
| 613 |
+
joint_feedback = ["π Excellent form!"]
|
| 614 |
+
elif final_score >= CONFIG['GOOD_THRESHOLD']:
|
| 615 |
+
joint_feedback = ["π Almost there, keep it up!"]
|
| 616 |
+
else:
|
| 617 |
+
joint_feedback = ["π Focus on alignment"]
|
| 618 |
+
|
| 619 |
+
return final_score, joint_feedback
|
| 620 |
+
|
| 621 |
def get_status(self, score):
|
| 622 |
if score >= CONFIG['PERFECT_THRESHOLD']:
|
| 623 |
return 'π Excellent'
|
|
|
|
| 629 |
return 'π Needs significant correction'
|
| 630 |
|
| 631 |
|
| 632 |
+
# βββ Initialize Components ββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
| 633 |
image_processor = ImageProcessor(CONFIG['TEMP_UPLOAD_DIR'])
|
| 634 |
custom_pose_manager = CustomPoseManager(CONFIG['USER_DATA_DIR'])
|
| 635 |
pose_generator = PoseGenerator()
|
| 636 |
reference_loader = PoseReferenceLoader(CONFIG['REFERENCE_FILE'])
|
| 637 |
comparison_engine = PoseComparisonEngine()
|
| 638 |
|
|
|
|
| 639 |
pose_reference_images = {}
|
| 640 |
|
|
|
|
| 641 |
def get_user_id() -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 642 |
if 'user_id' in session:
|
| 643 |
return session['user_id']
|
|
|
|
| 644 |
user_id = request.headers.get('X-User-ID')
|
| 645 |
if user_id:
|
|
|
|
| 646 |
user_dir = os.path.join(CONFIG['USER_DATA_DIR'], user_id)
|
| 647 |
if not os.path.exists(user_dir):
|
| 648 |
os.makedirs(user_dir, exist_ok=True)
|
| 649 |
return user_id
|
|
|
|
| 650 |
return 'anonymous'
|
| 651 |
|
|
|
|
| 652 |
def get_all_poses() -> List[Dict]:
|
|
|
|
| 653 |
user_id = get_user_id()
|
| 654 |
all_poses = reference_loader.get_all_poses()
|
| 655 |
+
|
|
|
|
| 656 |
custom_poses = custom_pose_manager.load_custom_poses(user_id)
|
| 657 |
for pose_id, data in custom_poses.items():
|
| 658 |
all_poses.append({
|
|
|
|
| 666 |
'generated_at': data.get('generated_at', None),
|
| 667 |
'similarity_score': data.get('similarity_score', None),
|
| 668 |
})
|
| 669 |
+
|
|
|
|
| 670 |
emoji_map = {
|
| 671 |
'downward-dog': 'π', 'warrior-2': 'βοΈ', 'tree': 'π³',
|
| 672 |
'cobra': 'π', 'mountain': 'ποΈ', 'childs-pose': 'π',
|
|
|
|
| 681 |
pose['steps'] = ['Position yourself in the pose', 'Hold the posture', 'Breathe deeply']
|
| 682 |
if not pose.get('difficulty'):
|
| 683 |
pose['difficulty'] = 'Beginner'
|
|
|
|
|
|
|
| 684 |
|
| 685 |
+
return sorted(all_poses, key=lambda x: x['name'])
|
| 686 |
|
| 687 |
def get_merged_poses() -> Dict:
|
|
|
|
| 688 |
user_id = get_user_id()
|
| 689 |
custom_poses = custom_pose_manager.load_custom_poses(user_id)
|
| 690 |
return reference_loader.merge_with_custom(custom_poses)
|
| 691 |
|
| 692 |
|
| 693 |
+
# βββ Authentication Routes ββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
| 694 |
|
| 695 |
@app.route('/api/register', methods=['POST'])
|
| 696 |
def register():
|
|
|
|
| 742 |
return jsonify({'user_id': user_id, 'name': data['name']})
|
| 743 |
return jsonify({'error': 'User not found'}), 404
|
| 744 |
|
| 745 |
+
|
| 746 |
+
# βββ API Routes ββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 747 |
|
| 748 |
@app.route('/')
|
| 749 |
def index():
|
| 750 |
return render_template('index.html')
|
| 751 |
|
|
|
|
| 752 |
@app.route('/api/poses', methods=['GET'])
|
| 753 |
def get_poses():
|
| 754 |
try:
|
|
|
|
| 759 |
logger.error(f"Error getting poses: {e}")
|
| 760 |
return jsonify([])
|
| 761 |
|
| 762 |
+
# βββ MODIFIED: References endpoint now includes extracted images βββ
|
| 763 |
@app.route('/api/pose/<pose_id>/references', methods=['GET'])
|
| 764 |
def get_pose_references(pose_id):
|
| 765 |
user_id = get_user_id()
|
| 766 |
images = []
|
| 767 |
+
|
| 768 |
+
# 1. Builtβin images from yoga/<pose_id>/
|
| 769 |
builtin_folder = os.path.join(CONFIG['YOGA_DIR'], pose_id)
|
| 770 |
if os.path.exists(builtin_folder):
|
| 771 |
for f in os.listdir(builtin_folder):
|
|
|
|
| 776 |
mime = 'image/jpeg' if f.endswith(('.jpg', '.jpeg')) else 'image/png'
|
| 777 |
images.append({'id': len(images), 'filename': f, 'data': img_data, 'mime': mime})
|
| 778 |
except Exception as e:
|
| 779 |
+
logger.error(f"Error loading builtβin reference image {f}: {e}")
|
| 780 |
+
|
| 781 |
+
# 2. Extracted dataset images from reference_images/<pose_id>/
|
| 782 |
+
ref_folder = os.path.join(CONFIG['REFERENCE_IMAGES_DIR'], pose_id)
|
| 783 |
+
if os.path.exists(ref_folder):
|
| 784 |
+
for f in sorted(os.listdir(ref_folder)):
|
| 785 |
+
if f.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')):
|
| 786 |
+
try:
|
| 787 |
+
with open(os.path.join(ref_folder, f), 'rb') as img_f:
|
| 788 |
+
img_data = base64.b64encode(img_f.read()).decode('utf-8')
|
| 789 |
+
mime = 'image/jpeg' if f.endswith(('.jpg', '.jpeg')) else 'image/png'
|
| 790 |
+
images.append({'id': len(images), 'filename': f, 'data': img_data, 'mime': mime})
|
| 791 |
+
except Exception as e:
|
| 792 |
+
logger.error(f"Error loading extracted reference image {f}: {e}")
|
| 793 |
+
|
| 794 |
+
# 3. Custom user images from user_data/<user_id>/images/<pose_id>/
|
| 795 |
custom_images = custom_pose_manager.get_custom_pose_images(user_id, pose_id)
|
| 796 |
for img_path in custom_images:
|
| 797 |
try:
|
|
|
|
| 800 |
images.append({'id': len(images), 'filename': os.path.basename(img_path), 'data': img_data, 'mime': 'image/jpeg'})
|
| 801 |
except Exception as e:
|
| 802 |
logger.error(f"Error loading custom reference image: {e}")
|
|
|
|
|
|
|
| 803 |
|
| 804 |
+
return jsonify({'references': images, 'count': len(images)})
|
| 805 |
|
| 806 |
+
# βββ Live Endpoint with Rate Limiting ββββββββββββββββββββββ
|
| 807 |
@app.route('/api/live', methods=['POST'])
|
| 808 |
def api_live():
|
| 809 |
+
client_key = request.headers.get('X-User-ID', request.remote_addr)
|
| 810 |
+
if not rate_limiter.is_allowed(client_key):
|
| 811 |
+
logger.warning(f"Rate limit exceeded for {client_key}")
|
| 812 |
+
return jsonify({'error': 'Too many requests. Please slow down.'}), 429
|
| 813 |
+
|
| 814 |
start_time = time.time()
|
| 815 |
try:
|
| 816 |
data = request.get_json(silent=True)
|
| 817 |
if not data or 'image' not in data or 'pose_id' not in data:
|
| 818 |
return jsonify({'error': 'Missing image or pose_id'}), 400
|
| 819 |
+
|
| 820 |
pose_id = data['pose_id']
|
| 821 |
image_b64 = data['image']
|
| 822 |
if ',' in image_b64:
|
| 823 |
image_b64 = image_b64.split(',', 1)[1]
|
| 824 |
+
|
| 825 |
try:
|
| 826 |
img_bytes = base64.b64decode(image_b64)
|
| 827 |
nparr = np.frombuffer(img_bytes, np.uint8)
|
|
|
|
| 829 |
except Exception as e:
|
| 830 |
logger.error(f"Image decode error: {e}")
|
| 831 |
return jsonify({'error': 'Invalid image data'}), 400
|
| 832 |
+
|
| 833 |
if img is None:
|
| 834 |
return jsonify({'error': 'Could not decode image'}), 400
|
| 835 |
+
|
| 836 |
img = cv2.resize(img, CONFIG['IMAGE_SIZE'])
|
| 837 |
rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 838 |
results = pose_live.process(rgb)
|
| 839 |
+
|
| 840 |
response_data = {
|
| 841 |
'score': 0,
|
| 842 |
'status': 'No person detected',
|
|
|
|
| 850 |
'processing_time': 0,
|
| 851 |
'landmarks': []
|
| 852 |
}
|
| 853 |
+
|
| 854 |
if results.pose_landmarks:
|
| 855 |
landmarks_data = [[lm.x, lm.y] for lm in results.pose_landmarks.landmark]
|
| 856 |
landmarks = np.array(landmarks_data)
|
| 857 |
+
|
| 858 |
merged_db = get_merged_poses()
|
| 859 |
+
|
| 860 |
if pose_id not in merged_db:
|
| 861 |
response_data['suggestions'] = [f'Pose "{pose_id}" not found', 'Try using Add Pose']
|
| 862 |
response_data['landmarks'] = landmarks_data
|
|
|
|
| 866 |
score, joint_feedback = comparison_engine.compare(current_angles, pose_id, merged_db)
|
| 867 |
score = int(round(score))
|
| 868 |
status = comparison_engine.get_status(score)
|
| 869 |
+
|
| 870 |
+
suggestions = joint_feedback[:5]
|
| 871 |
+
if not suggestions:
|
| 872 |
+
suggestions = ['Keep practicing!']
|
| 873 |
+
|
| 874 |
if score >= CONFIG['PERFECT_THRESHOLD']:
|
| 875 |
+
suggestions.insert(0, 'π Excellent! Perfect form!')
|
|
|
|
| 876 |
elif score >= CONFIG['GOOD_THRESHOLD']:
|
| 877 |
+
suggestions.insert(0, 'π Good! Almost perfect!')
|
|
|
|
| 878 |
else:
|
| 879 |
+
suggestions.insert(0, 'π Focus on these corrections:')
|
| 880 |
+
|
|
|
|
|
|
|
|
|
|
| 881 |
color = (34, 197, 94) if score >= 80 else (245, 158, 11) if score >= 65 else (239, 68, 68)
|
| 882 |
drawing_spec = mp_drawing.DrawingSpec(color=color, thickness=2, circle_radius=3)
|
| 883 |
mp_drawing.draw_landmarks(img, results.pose_landmarks, mp_pose.POSE_CONNECTIONS, drawing_spec, drawing_spec)
|
| 884 |
+
|
| 885 |
response_data = {
|
| 886 |
'score': score,
|
| 887 |
'status': status,
|
|
|
|
| 900 |
'Stand back so camera captures head to feet',
|
| 901 |
'Ensure good lighting'
|
| 902 |
]
|
| 903 |
+
|
| 904 |
_, buffer = cv2.imencode('.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, CONFIG['JPEG_QUALITY']])
|
| 905 |
response_data['image'] = base64.b64encode(buffer).decode('utf-8')
|
| 906 |
response_data['processing_time'] = int((time.time() - start_time) * 1000)
|
| 907 |
+
|
| 908 |
return jsonify(response_data)
|
| 909 |
+
|
| 910 |
except Exception as e:
|
| 911 |
logger.error(f"API Live error: {e}", exc_info=True)
|
| 912 |
return jsonify({'error': str(e), 'score': 0, 'status': 'Error', 'suggestions': ['An error occurred'], 'landmarks': []}), 500
|
| 913 |
|
| 914 |
+
# βββ Generate and Save Custom Poses ββββββββββββββββββββββ
|
| 915 |
|
| 916 |
@app.route('/api/generate-pose', methods=['POST'])
|
| 917 |
def generate_pose():
|
|
|
|
| 920 |
name = request.form.get('name', '').strip()
|
| 921 |
if not name:
|
| 922 |
return jsonify({'error': 'Pose name is required'}), 400
|
| 923 |
+
|
| 924 |
category = request.form.get('category', 'General')
|
| 925 |
difficulty = request.form.get('difficulty', 'Beginner')
|
| 926 |
+
|
| 927 |
image_paths = []
|
| 928 |
for i in range(5):
|
| 929 |
file_key = f'image_{i}'
|
| 930 |
if file_key not in request.files:
|
| 931 |
logger.error(f"Missing image {i+1}")
|
| 932 |
return jsonify({'error': f'Missing image {i+1}'}), 400
|
| 933 |
+
|
| 934 |
file = request.files[file_key]
|
| 935 |
if file.filename == '':
|
| 936 |
logger.error(f"Empty file for image {i+1}")
|
| 937 |
return jsonify({'error': f'Empty file for image {i+1}'}), 400
|
| 938 |
+
|
| 939 |
logger.info(f"π₯ Received image {i+1}: {file.filename}")
|
| 940 |
temp_path = image_processor.save_temp_image(file.read(), file.filename)
|
| 941 |
if not temp_path:
|
| 942 |
logger.error(f"Failed to save image {i+1}")
|
| 943 |
return jsonify({'error': f'Failed to save image {i+1}'}), 400
|
| 944 |
+
|
| 945 |
image_paths.append(temp_path)
|
| 946 |
logger.info(f"β
Saved to: {temp_path}")
|
| 947 |
+
|
| 948 |
result = pose_generator.generate_pose_reference(
|
| 949 |
image_paths=image_paths,
|
| 950 |
pose_name=name,
|
| 951 |
difficulty=difficulty,
|
| 952 |
category=category
|
| 953 |
)
|
| 954 |
+
|
| 955 |
for path in image_paths:
|
| 956 |
image_processor.delete_temp_file(path)
|
| 957 |
+
|
| 958 |
if result is None:
|
| 959 |
logger.error("Generation result is None")
|
| 960 |
return jsonify({'error': 'Failed to generate pose'}), 400
|
| 961 |
+
|
| 962 |
if 'error' in result:
|
| 963 |
logger.error(f"Generation error: {result['error']}")
|
| 964 |
return jsonify({'error': result['error']}), 400
|
| 965 |
+
|
| 966 |
result['pose_name'] = name
|
| 967 |
result['category'] = category
|
| 968 |
result['difficulty'] = difficulty
|
| 969 |
+
|
| 970 |
logger.info(f"β
Pose generated successfully: {name}")
|
| 971 |
return jsonify(result)
|
| 972 |
+
|
| 973 |
except Exception as e:
|
| 974 |
logger.error(f"Error generating pose: {e}", exc_info=True)
|
| 975 |
return jsonify({'error': str(e)}), 500
|
| 976 |
|
|
|
|
| 977 |
@app.route('/api/save-custom-pose', methods=['POST'])
|
| 978 |
def save_custom_pose():
|
| 979 |
try:
|
| 980 |
data = request.get_json()
|
| 981 |
if not data:
|
| 982 |
return jsonify({'error': 'No data provided'}), 400
|
| 983 |
+
|
| 984 |
pose_id = data.get('pose_id')
|
| 985 |
reference = data.get('reference')
|
| 986 |
name = data.get('name', pose_id)
|
| 987 |
+
|
| 988 |
if not pose_id or not reference:
|
| 989 |
return jsonify({'error': 'Missing pose_id or reference'}), 400
|
| 990 |
+
|
| 991 |
if 'angles' not in reference:
|
| 992 |
return jsonify({'error': 'Invalid reference: missing "angles"'}), 400
|
| 993 |
+
|
| 994 |
user_id = get_user_id()
|
| 995 |
logger.info(f"πΎ Saving custom pose '{name}' (ID: {pose_id}) for user {user_id[:8]}")
|
| 996 |
+
|
| 997 |
success = custom_pose_manager.add_custom_pose(
|
| 998 |
user_id=user_id,
|
| 999 |
pose_id=pose_id,
|
| 1000 |
reference=reference,
|
| 1001 |
images=[]
|
| 1002 |
)
|
| 1003 |
+
|
| 1004 |
if not success:
|
| 1005 |
logger.error("Failed to save custom pose")
|
| 1006 |
return jsonify({'error': 'Failed to save pose'}), 500
|
| 1007 |
+
|
|
|
|
| 1008 |
global pose_reference_images
|
| 1009 |
cache_key = f"{user_id}_{pose_id}"
|
| 1010 |
if cache_key in pose_reference_images:
|
| 1011 |
del pose_reference_images[cache_key]
|
| 1012 |
logger.info(f"ποΈ Invalidated cache for {cache_key}")
|
| 1013 |
+
|
| 1014 |
logger.info(f"β
Pose '{name}' saved successfully")
|
| 1015 |
return jsonify({
|
| 1016 |
'success': True,
|
| 1017 |
'message': f'Pose "{name}" saved successfully',
|
| 1018 |
'pose_id': pose_id
|
| 1019 |
})
|
| 1020 |
+
|
| 1021 |
except Exception as e:
|
| 1022 |
logger.error(f"Error saving custom pose: {e}", exc_info=True)
|
| 1023 |
return jsonify({'error': str(e)}), 500
|
| 1024 |
|
|
|
|
| 1025 |
@app.route('/api/custom-poses', methods=['GET'])
|
| 1026 |
def get_custom_poses():
|
| 1027 |
user_id = get_user_id()
|
| 1028 |
poses = custom_pose_manager.load_custom_poses(user_id)
|
| 1029 |
return jsonify(poses)
|
| 1030 |
|
|
|
|
| 1031 |
@app.route('/api/health', methods=['GET'])
|
| 1032 |
def health_check():
|
| 1033 |
user_id = get_user_id()
|
|
|
|
| 1038 |
'custom_poses': len(custom_pose_manager.load_custom_poses(user_id)),
|
| 1039 |
})
|
| 1040 |
|
| 1041 |
+
# βββ Main Entry Point ββββββββββββββββββββββββββββββββββββββ
|
| 1042 |
|
|
|
|
|
|
|
|
|
|
| 1043 |
if __name__ == '__main__':
|
| 1044 |
logger.info("=" * 60)
|
| 1045 |
logger.info("π§ YogaMate Server Starting...")
|
| 1046 |
logger.info(f"π Built-in poses: {len(reference_loader.pose_database)}")
|
| 1047 |
logger.info("=" * 60)
|
| 1048 |
+
|
|
|
|
| 1049 |
image_processor.cleanup_temp_dir()
|
| 1050 |
+
|
| 1051 |
app.run(
|
| 1052 |
host='0.0.0.0',
|
| 1053 |
port=7860,
|