Spaces:
Paused
Paused
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,703 +1,763 @@
|
|
| 1 |
-
"""
|
| 2 |
-
π FunCaptcha Solver API - Hugging Face Spaces Deployment
|
| 3 |
-
Optimized for speed, memory efficiency, and scalability
|
| 4 |
-
|
| 5 |
-
Features:
|
| 6 |
-
- FastAPI async operations
|
| 7 |
-
- API key authentication via HF secrets
|
| 8 |
-
- Fuzzy label matching
|
| 9 |
-
- Memory-efficient model loading
|
| 10 |
-
- ONNX CPU optimization
|
| 11 |
-
- Request caching for performance
|
| 12 |
-
"""
|
| 13 |
-
|
| 14 |
-
import os
|
| 15 |
-
import io
|
| 16 |
-
import base64
|
| 17 |
-
import hashlib
|
| 18 |
-
import asyncio
|
| 19 |
-
from datetime import datetime
|
| 20 |
-
from typing import Optional, Dict, Any, List
|
| 21 |
-
import logging
|
| 22 |
-
|
| 23 |
-
import cv2
|
| 24 |
-
import numpy as np
|
| 25 |
-
from PIL import Image
|
| 26 |
-
import yaml
|
| 27 |
-
import difflib
|
| 28 |
-
|
| 29 |
-
# Try to import ML backends dengan multiple fallbacks
|
| 30 |
-
ONNX_AVAILABLE = False
|
| 31 |
-
TORCH_AVAILABLE = False
|
| 32 |
-
TF_AVAILABLE = False
|
| 33 |
-
ort = None
|
| 34 |
-
|
| 35 |
-
# Try ONNX Runtime first
|
| 36 |
-
try:
|
| 37 |
-
import onnxruntime as ort
|
| 38 |
-
ONNX_AVAILABLE = True
|
| 39 |
-
print("β
ONNX Runtime imported successfully")
|
| 40 |
-
except ImportError as e:
|
| 41 |
-
print(f"β ONNX Runtime import failed: {e}")
|
| 42 |
-
|
| 43 |
-
# Try PyTorch as fallback
|
| 44 |
-
try:
|
| 45 |
-
import torch
|
| 46 |
-
TORCH_AVAILABLE = True
|
| 47 |
-
print("β
PyTorch imported as ONNX Runtime alternative")
|
| 48 |
-
except ImportError:
|
| 49 |
-
print("β PyTorch not available")
|
| 50 |
-
|
| 51 |
-
# Try TensorFlow as final fallback
|
| 52 |
-
try:
|
| 53 |
-
import tensorflow as tf
|
| 54 |
-
TF_AVAILABLE = True
|
| 55 |
-
print("β
TensorFlow imported as ONNX Runtime alternative")
|
| 56 |
-
except ImportError:
|
| 57 |
-
print("β TensorFlow not available")
|
| 58 |
-
print("β οΈ Running without ML backend - model inference will be disabled")
|
| 59 |
-
|
| 60 |
-
ML_BACKEND_AVAILABLE = ONNX_AVAILABLE or TORCH_AVAILABLE or TF_AVAILABLE
|
| 61 |
-
|
| 62 |
-
from fastapi import FastAPI, HTTPException, Depends, status
|
| 63 |
-
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 64 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 65 |
-
from pydantic import BaseModel, Field
|
| 66 |
-
import uvicorn
|
| 67 |
-
|
| 68 |
-
# Configure logging
|
| 69 |
-
logging.basicConfig(level=logging.INFO)
|
| 70 |
-
logger = logging.getLogger(__name__)
|
| 71 |
-
|
| 72 |
-
# =================================================================
|
| 73 |
-
# CONFIGURATION & MODELS
|
| 74 |
-
# =================================================================
|
| 75 |
-
|
| 76 |
-
class FunCaptchaRequest(BaseModel):
|
| 77 |
-
"""Request model untuk FunCaptcha solving"""
|
| 78 |
-
challenge_type: str = Field(..., description="Type of challenge (pick_the, upright)")
|
| 79 |
-
image_b64: str = Field(..., description="Base64 encoded image")
|
| 80 |
-
target_label: Optional[str] = Field(None, description="Target label untuk pick_the challenges")
|
| 81 |
-
|
| 82 |
-
class FunCaptchaResponse(BaseModel):
|
| 83 |
-
"""Response model untuk FunCaptcha solving"""
|
| 84 |
-
status: str = Field(..., description="Status: success, not_found, error")
|
| 85 |
-
box: Optional[List[float]] = Field(None, description="Bounding box coordinates [x, y, w, h]")
|
| 86 |
-
button_index: Optional[int] = Field(None, description="Button index untuk upright challenges")
|
| 87 |
-
confidence: Optional[float] = Field(None, description="Detection confidence")
|
| 88 |
-
message: Optional[str] = Field(None, description="Additional message")
|
| 89 |
-
processing_time: Optional[float] = Field(None, description="Processing time in seconds")
|
| 90 |
-
|
| 91 |
-
# =================================================================
|
| 92 |
-
# AUTHENTICATION
|
| 93 |
-
# =================================================================
|
| 94 |
-
|
| 95 |
-
security = HTTPBearer()
|
| 96 |
-
|
| 97 |
-
def get_api_key_from_secrets() -> str:
|
| 98 |
-
"""Get API key dari Hugging Face Secrets"""
|
| 99 |
-
api_key = os.getenv("FUNCAPTCHA_API_KEY")
|
| 100 |
-
if not api_key:
|
| 101 |
-
logger.error("FUNCAPTCHA_API_KEY not found in environment variables")
|
| 102 |
-
raise ValueError("API key tidak ditemukan dalam HF Secrets")
|
| 103 |
-
return api_key
|
| 104 |
-
|
| 105 |
-
def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)) -> bool:
|
| 106 |
-
"""Verify API key dari request header"""
|
| 107 |
-
expected_key = get_api_key_from_secrets()
|
| 108 |
-
if credentials.credentials != expected_key:
|
| 109 |
-
raise HTTPException(
|
| 110 |
-
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 111 |
-
detail="Invalid API key",
|
| 112 |
-
headers={"WWW-Authenticate": "Bearer"}
|
| 113 |
-
)
|
| 114 |
-
return True
|
| 115 |
-
|
| 116 |
-
# =================================================================
|
| 117 |
-
# MODEL CONFIGURATION & MANAGEMENT
|
| 118 |
-
# =================================================================
|
| 119 |
-
|
| 120 |
-
CONFIGS = {
|
| 121 |
-
'default': {
|
| 122 |
-
'model_path': 'best.onnx',
|
| 123 |
-
'yaml_path': 'data.yaml',
|
| 124 |
-
'input_size': 640,
|
| 125 |
-
'confidence_threshold': 0.4,
|
| 126 |
-
'nms_threshold': 0.2
|
| 127 |
-
},
|
| 128 |
-
'spiral_galaxy': {
|
| 129 |
-
'model_path': 'bestspiral.onnx',
|
| 130 |
-
'yaml_path': 'dataspiral.yaml',
|
| 131 |
-
'input_size': 416,
|
| 132 |
-
'confidence_threshold': 0.30,
|
| 133 |
-
'nms_threshold': 0.45
|
| 134 |
-
},
|
| 135 |
-
'upright': {
|
| 136 |
-
'model_path': '
|
| 137 |
-
'yaml_path': 'data_upright.yaml',
|
| 138 |
-
'input_size': 640,
|
| 139 |
-
'confidence_threshold': 0.45,
|
| 140 |
-
'nms_threshold': 0.45
|
| 141 |
-
}
|
| 142 |
-
}
|
| 143 |
-
|
| 144 |
-
MODEL_ROUTING = [
|
| 145 |
-
(['spiral', 'galaxy'], 'spiral_galaxy')
|
| 146 |
-
]
|
| 147 |
-
|
| 148 |
-
# Global cache untuk models dan responses
|
| 149 |
-
LOADED_MODELS: Dict[str, Dict[str, Any]] = {}
|
| 150 |
-
RESPONSE_CACHE: Dict[str, Dict[str, Any]] = {}
|
| 151 |
-
CACHE_MAX_SIZE = 100
|
| 152 |
-
|
| 153 |
-
class ModelManager:
|
| 154 |
-
"""Manager untuk loading dan caching models"""
|
| 155 |
-
|
| 156 |
-
@staticmethod
|
| 157 |
-
async def get_model(config_key: str) -> Optional[Dict[str, Any]]:
|
| 158 |
-
"""Load model dengan caching untuk efficiency"""
|
| 159 |
-
# Check if any ML backend is available
|
| 160 |
-
if not ML_BACKEND_AVAILABLE:
|
| 161 |
-
logger.error("β No ML backend available - cannot load models")
|
| 162 |
-
return None
|
| 163 |
-
|
| 164 |
-
if config_key not in LOADED_MODELS:
|
| 165 |
-
logger.info(f"Loading model: {config_key}")
|
| 166 |
-
|
| 167 |
-
try:
|
| 168 |
-
config = CONFIGS[config_key]
|
| 169 |
-
|
| 170 |
-
# Check if files exist
|
| 171 |
-
if not os.path.exists(config['model_path']):
|
| 172 |
-
logger.warning(f"Model file not found: {config['model_path']}")
|
| 173 |
-
return None
|
| 174 |
-
|
| 175 |
-
if not os.path.exists(config['yaml_path']):
|
| 176 |
-
logger.warning(f"YAML file not found: {config['yaml_path']}")
|
| 177 |
-
return None
|
| 178 |
-
|
| 179 |
-
# Load model dengan available backend
|
| 180 |
-
session = None
|
| 181 |
-
|
| 182 |
-
if ONNX_AVAILABLE:
|
| 183 |
-
# Load ONNX session dengan CPU optimization
|
| 184 |
-
providers = ['CPUExecutionProvider']
|
| 185 |
-
session_options = ort.SessionOptions()
|
| 186 |
-
session_options.intra_op_num_threads = 2 # Optimize untuk CPU
|
| 187 |
-
session_options.inter_op_num_threads = 2
|
| 188 |
-
session_options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
|
| 189 |
-
session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 190 |
-
|
| 191 |
-
session = ort.InferenceSession(
|
| 192 |
-
config['model_path'],
|
| 193 |
-
providers=providers,
|
| 194 |
-
sess_options=session_options
|
| 195 |
-
)
|
| 196 |
-
else:
|
| 197 |
-
# For now, only ONNX Runtime is supported for model loading
|
| 198 |
-
# PyTorch/TensorFlow alternatives would need model conversion
|
| 199 |
-
logger.error("β ONNX models require ONNX Runtime - other backends not yet implemented")
|
| 200 |
-
return None
|
| 201 |
-
|
| 202 |
-
# Load class names
|
| 203 |
-
with open(config['yaml_path'], 'r', encoding='utf-8') as file:
|
| 204 |
-
class_names = yaml.safe_load(file)['names']
|
| 205 |
-
|
| 206 |
-
LOADED_MODELS[config_key] = {
|
| 207 |
-
'session': session,
|
| 208 |
-
'class_names': class_names,
|
| 209 |
-
'input_name': session.get_inputs()[0].name,
|
| 210 |
-
'input_size': config['input_size'],
|
| 211 |
-
'confidence': config['confidence_threshold'],
|
| 212 |
-
'nms': config.get('nms_threshold', 0.45)
|
| 213 |
-
}
|
| 214 |
-
|
| 215 |
-
logger.info(f"β
Model loaded successfully: {config_key}")
|
| 216 |
-
|
| 217 |
-
except Exception as e:
|
| 218 |
-
logger.error(f"β Error loading model {config_key}: {e}")
|
| 219 |
-
return None
|
| 220 |
-
|
| 221 |
-
return LOADED_MODELS[config_key]
|
| 222 |
-
|
| 223 |
-
# =================================================================
|
| 224 |
-
# IMAGE PROCESSING & UTILITIES
|
| 225 |
-
# =================================================================
|
| 226 |
-
|
| 227 |
-
def preprocess_image(image_bytes: bytes, input_size: int) -> np.ndarray:
|
| 228 |
-
"""Preprocess image untuk ONNX inference dengan optimasi memory"""
|
| 229 |
-
image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
|
| 230 |
-
image_np = np.array(image)
|
| 231 |
-
h, w, _ = image_np.shape
|
| 232 |
-
|
| 233 |
-
scale = min(input_size / w, input_size / h)
|
| 234 |
-
new_w, new_h = int(w * scale), int(h * scale)
|
| 235 |
-
|
| 236 |
-
resized_image = cv2.resize(image_np, (new_w, new_h))
|
| 237 |
-
padded_image = np.full((input_size, input_size, 3), 114, dtype=np.uint8)
|
| 238 |
-
|
| 239 |
-
# Calculate padding
|
| 240 |
-
y_offset = (input_size - new_h) // 2
|
| 241 |
-
x_offset = (input_size - new_w) // 2
|
| 242 |
-
|
| 243 |
-
padded_image[y_offset:y_offset + new_h, x_offset:x_offset + new_w, :] = resized_image
|
| 244 |
-
|
| 245 |
-
# Convert untuk ONNX
|
| 246 |
-
input_tensor = padded_image.astype(np.float32) / 255.0
|
| 247 |
-
input_tensor = np.transpose(input_tensor, (2, 0, 1))
|
| 248 |
-
input_tensor = np.expand_dims(input_tensor, axis=0)
|
| 249 |
-
|
| 250 |
-
return input_tensor
|
| 251 |
-
|
| 252 |
-
def fuzzy_match_label(target_label: str, class_names: List[str], threshold: float = 0.6) -> Optional[str]:
|
| 253 |
-
"""Fuzzy matching untuk label variations"""
|
| 254 |
-
target_normalized = target_label.lower().strip()
|
| 255 |
-
|
| 256 |
-
# Dictionary untuk common variations
|
| 257 |
-
label_variants = {
|
| 258 |
-
'ice cream': ['ice cream', 'icecream', 'ice'],
|
| 259 |
-
'hotdog': ['hot dog', 'hotdog', 'hot-dog'],
|
| 260 |
-
'hot dog': ['hot dog', 'hotdog', 'hot-dog'],
|
| 261 |
-
'sunglasses': ['sunglasses', 'sun glasses', 'sunglass'],
|
| 262 |
-
'sun glasses': ['sunglasses', 'sun glasses', 'sunglass']
|
| 263 |
-
}
|
| 264 |
-
|
| 265 |
-
# 1. Exact match
|
| 266 |
-
if target_normalized in class_names:
|
| 267 |
-
return target_normalized
|
| 268 |
-
|
| 269 |
-
# 2. Check known variants
|
| 270 |
-
for main_label, variants in label_variants.items():
|
| 271 |
-
if target_normalized in variants and main_label in class_names:
|
| 272 |
-
return main_label
|
| 273 |
-
|
| 274 |
-
# 3. Fuzzy matching
|
| 275 |
-
best_matches = difflib.get_close_matches(
|
| 276 |
-
target_normalized,
|
| 277 |
-
[name.lower() for name in class_names],
|
| 278 |
-
n=3,
|
| 279 |
-
cutoff=threshold
|
| 280 |
-
)
|
| 281 |
-
|
| 282 |
-
if best_matches:
|
| 283 |
-
for match in best_matches:
|
| 284 |
-
for class_name in class_names:
|
| 285 |
-
if class_name.lower() == match:
|
| 286 |
-
return class_name
|
| 287 |
-
|
| 288 |
-
# 4. Partial matching
|
| 289 |
-
for class_name in class_names:
|
| 290 |
-
if target_normalized in class_name.lower() or class_name.lower() in target_normalized:
|
| 291 |
-
return class_name
|
| 292 |
-
|
| 293 |
-
return None
|
| 294 |
-
|
| 295 |
-
def get_config_key_for_label(target_label: str) -> str:
|
| 296 |
-
"""Determine which model config to use"""
|
| 297 |
-
for keywords, config_key in MODEL_ROUTING:
|
| 298 |
-
if any(keyword in target_label for keyword in keywords):
|
| 299 |
-
return config_key
|
| 300 |
-
return 'default'
|
| 301 |
-
|
| 302 |
-
def get_button_index(x_center: float, y_center: float, img_width: int, img_height: int,
|
| 303 |
-
grid_cols: int = 3, grid_rows: int = 2) -> int:
|
| 304 |
-
"""Calculate button index dari coordinates"""
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
#
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
"
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
}
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
)
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
"""
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
π FunCaptcha Solver API - Hugging Face Spaces Deployment
|
| 3 |
+
Optimized for speed, memory efficiency, and scalability
|
| 4 |
+
|
| 5 |
+
Features:
|
| 6 |
+
- FastAPI async operations
|
| 7 |
+
- API key authentication via HF secrets
|
| 8 |
+
- Fuzzy label matching
|
| 9 |
+
- Memory-efficient model loading
|
| 10 |
+
- ONNX CPU optimization
|
| 11 |
+
- Request caching for performance
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
import io
|
| 16 |
+
import base64
|
| 17 |
+
import hashlib
|
| 18 |
+
import asyncio
|
| 19 |
+
from datetime import datetime
|
| 20 |
+
from typing import Optional, Dict, Any, List
|
| 21 |
+
import logging
|
| 22 |
+
|
| 23 |
+
import cv2
|
| 24 |
+
import numpy as np
|
| 25 |
+
from PIL import Image
|
| 26 |
+
import yaml
|
| 27 |
+
import difflib
|
| 28 |
+
|
| 29 |
+
# Try to import ML backends dengan multiple fallbacks
|
| 30 |
+
ONNX_AVAILABLE = False
|
| 31 |
+
TORCH_AVAILABLE = False
|
| 32 |
+
TF_AVAILABLE = False
|
| 33 |
+
ort = None
|
| 34 |
+
|
| 35 |
+
# Try ONNX Runtime first
|
| 36 |
+
try:
|
| 37 |
+
import onnxruntime as ort
|
| 38 |
+
ONNX_AVAILABLE = True
|
| 39 |
+
print("β
ONNX Runtime imported successfully")
|
| 40 |
+
except ImportError as e:
|
| 41 |
+
print(f"β ONNX Runtime import failed: {e}")
|
| 42 |
+
|
| 43 |
+
# Try PyTorch as fallback
|
| 44 |
+
try:
|
| 45 |
+
import torch
|
| 46 |
+
TORCH_AVAILABLE = True
|
| 47 |
+
print("β
PyTorch imported as ONNX Runtime alternative")
|
| 48 |
+
except ImportError:
|
| 49 |
+
print("β PyTorch not available")
|
| 50 |
+
|
| 51 |
+
# Try TensorFlow as final fallback
|
| 52 |
+
try:
|
| 53 |
+
import tensorflow as tf
|
| 54 |
+
TF_AVAILABLE = True
|
| 55 |
+
print("β
TensorFlow imported as ONNX Runtime alternative")
|
| 56 |
+
except ImportError:
|
| 57 |
+
print("β TensorFlow not available")
|
| 58 |
+
print("β οΈ Running without ML backend - model inference will be disabled")
|
| 59 |
+
|
| 60 |
+
ML_BACKEND_AVAILABLE = ONNX_AVAILABLE or TORCH_AVAILABLE or TF_AVAILABLE
|
| 61 |
+
|
| 62 |
+
from fastapi import FastAPI, HTTPException, Depends, status
|
| 63 |
+
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 64 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 65 |
+
from pydantic import BaseModel, Field
|
| 66 |
+
import uvicorn
|
| 67 |
+
|
| 68 |
+
# Configure logging
|
| 69 |
+
logging.basicConfig(level=logging.INFO)
|
| 70 |
+
logger = logging.getLogger(__name__)
|
| 71 |
+
|
| 72 |
+
# =================================================================
|
| 73 |
+
# CONFIGURATION & MODELS
|
| 74 |
+
# =================================================================
|
| 75 |
+
|
| 76 |
+
class FunCaptchaRequest(BaseModel):
|
| 77 |
+
"""Request model untuk FunCaptcha solving"""
|
| 78 |
+
challenge_type: str = Field(..., description="Type of challenge (pick_the, upright)")
|
| 79 |
+
image_b64: str = Field(..., description="Base64 encoded image")
|
| 80 |
+
target_label: Optional[str] = Field(None, description="Target label untuk pick_the challenges")
|
| 81 |
+
|
| 82 |
+
class FunCaptchaResponse(BaseModel):
|
| 83 |
+
"""Response model untuk FunCaptcha solving"""
|
| 84 |
+
status: str = Field(..., description="Status: success, not_found, error")
|
| 85 |
+
box: Optional[List[float]] = Field(None, description="Bounding box coordinates [x, y, w, h]")
|
| 86 |
+
button_index: Optional[int] = Field(None, description="Button index untuk upright challenges")
|
| 87 |
+
confidence: Optional[float] = Field(None, description="Detection confidence")
|
| 88 |
+
message: Optional[str] = Field(None, description="Additional message")
|
| 89 |
+
processing_time: Optional[float] = Field(None, description="Processing time in seconds")
|
| 90 |
+
|
| 91 |
+
# =================================================================
|
| 92 |
+
# AUTHENTICATION
|
| 93 |
+
# =================================================================
|
| 94 |
+
|
| 95 |
+
security = HTTPBearer()
|
| 96 |
+
|
| 97 |
+
def get_api_key_from_secrets() -> str:
|
| 98 |
+
"""Get API key dari Hugging Face Secrets"""
|
| 99 |
+
api_key = os.getenv("FUNCAPTCHA_API_KEY")
|
| 100 |
+
if not api_key:
|
| 101 |
+
logger.error("FUNCAPTCHA_API_KEY not found in environment variables")
|
| 102 |
+
raise ValueError("API key tidak ditemukan dalam HF Secrets")
|
| 103 |
+
return api_key
|
| 104 |
+
|
| 105 |
+
def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)) -> bool:
|
| 106 |
+
"""Verify API key dari request header"""
|
| 107 |
+
expected_key = get_api_key_from_secrets()
|
| 108 |
+
if credentials.credentials != expected_key:
|
| 109 |
+
raise HTTPException(
|
| 110 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 111 |
+
detail="Invalid API key",
|
| 112 |
+
headers={"WWW-Authenticate": "Bearer"}
|
| 113 |
+
)
|
| 114 |
+
return True
|
| 115 |
+
|
| 116 |
+
# =================================================================
|
| 117 |
+
# MODEL CONFIGURATION & MANAGEMENT
|
| 118 |
+
# =================================================================
|
| 119 |
+
|
| 120 |
+
CONFIGS = {
|
| 121 |
+
'default': {
|
| 122 |
+
'model_path': 'best.onnx',
|
| 123 |
+
'yaml_path': 'data.yaml',
|
| 124 |
+
'input_size': 640,
|
| 125 |
+
'confidence_threshold': 0.4,
|
| 126 |
+
'nms_threshold': 0.2
|
| 127 |
+
},
|
| 128 |
+
'spiral_galaxy': {
|
| 129 |
+
'model_path': 'bestspiral.onnx',
|
| 130 |
+
'yaml_path': 'dataspiral.yaml',
|
| 131 |
+
'input_size': 416,
|
| 132 |
+
'confidence_threshold': 0.30,
|
| 133 |
+
'nms_threshold': 0.45
|
| 134 |
+
},
|
| 135 |
+
'upright': {
|
| 136 |
+
'model_path': 'best_upright.onnx',
|
| 137 |
+
'yaml_path': 'data_upright.yaml',
|
| 138 |
+
'input_size': 640,
|
| 139 |
+
'confidence_threshold': 0.45,
|
| 140 |
+
'nms_threshold': 0.45
|
| 141 |
+
}
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
MODEL_ROUTING = [
|
| 145 |
+
(['spiral', 'galaxy'], 'spiral_galaxy')
|
| 146 |
+
]
|
| 147 |
+
|
| 148 |
+
# Global cache untuk models dan responses
|
| 149 |
+
LOADED_MODELS: Dict[str, Dict[str, Any]] = {}
|
| 150 |
+
RESPONSE_CACHE: Dict[str, Dict[str, Any]] = {}
|
| 151 |
+
CACHE_MAX_SIZE = 100
|
| 152 |
+
|
| 153 |
+
class ModelManager:
|
| 154 |
+
"""Manager untuk loading dan caching models"""
|
| 155 |
+
|
| 156 |
+
@staticmethod
|
| 157 |
+
async def get_model(config_key: str) -> Optional[Dict[str, Any]]:
|
| 158 |
+
"""Load model dengan caching untuk efficiency"""
|
| 159 |
+
# Check if any ML backend is available
|
| 160 |
+
if not ML_BACKEND_AVAILABLE:
|
| 161 |
+
logger.error("β No ML backend available - cannot load models")
|
| 162 |
+
return None
|
| 163 |
+
|
| 164 |
+
if config_key not in LOADED_MODELS:
|
| 165 |
+
logger.info(f"Loading model: {config_key}")
|
| 166 |
+
|
| 167 |
+
try:
|
| 168 |
+
config = CONFIGS[config_key]
|
| 169 |
+
|
| 170 |
+
# Check if files exist
|
| 171 |
+
if not os.path.exists(config['model_path']):
|
| 172 |
+
logger.warning(f"Model file not found: {config['model_path']}")
|
| 173 |
+
return None
|
| 174 |
+
|
| 175 |
+
if not os.path.exists(config['yaml_path']):
|
| 176 |
+
logger.warning(f"YAML file not found: {config['yaml_path']}")
|
| 177 |
+
return None
|
| 178 |
+
|
| 179 |
+
# Load model dengan available backend
|
| 180 |
+
session = None
|
| 181 |
+
|
| 182 |
+
if ONNX_AVAILABLE:
|
| 183 |
+
# Load ONNX session dengan CPU optimization
|
| 184 |
+
providers = ['CPUExecutionProvider']
|
| 185 |
+
session_options = ort.SessionOptions()
|
| 186 |
+
session_options.intra_op_num_threads = 2 # Optimize untuk CPU
|
| 187 |
+
session_options.inter_op_num_threads = 2
|
| 188 |
+
session_options.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
|
| 189 |
+
session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 190 |
+
|
| 191 |
+
session = ort.InferenceSession(
|
| 192 |
+
config['model_path'],
|
| 193 |
+
providers=providers,
|
| 194 |
+
sess_options=session_options
|
| 195 |
+
)
|
| 196 |
+
else:
|
| 197 |
+
# For now, only ONNX Runtime is supported for model loading
|
| 198 |
+
# PyTorch/TensorFlow alternatives would need model conversion
|
| 199 |
+
logger.error("β ONNX models require ONNX Runtime - other backends not yet implemented")
|
| 200 |
+
return None
|
| 201 |
+
|
| 202 |
+
# Load class names
|
| 203 |
+
with open(config['yaml_path'], 'r', encoding='utf-8') as file:
|
| 204 |
+
class_names = yaml.safe_load(file)['names']
|
| 205 |
+
|
| 206 |
+
LOADED_MODELS[config_key] = {
|
| 207 |
+
'session': session,
|
| 208 |
+
'class_names': class_names,
|
| 209 |
+
'input_name': session.get_inputs()[0].name,
|
| 210 |
+
'input_size': config['input_size'],
|
| 211 |
+
'confidence': config['confidence_threshold'],
|
| 212 |
+
'nms': config.get('nms_threshold', 0.45)
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
logger.info(f"β
Model loaded successfully: {config_key}")
|
| 216 |
+
|
| 217 |
+
except Exception as e:
|
| 218 |
+
logger.error(f"β Error loading model {config_key}: {e}")
|
| 219 |
+
return None
|
| 220 |
+
|
| 221 |
+
return LOADED_MODELS[config_key]
|
| 222 |
+
|
| 223 |
+
# =================================================================
|
| 224 |
+
# IMAGE PROCESSING & UTILITIES
|
| 225 |
+
# =================================================================
|
| 226 |
+
|
| 227 |
+
def preprocess_image(image_bytes: bytes, input_size: int) -> np.ndarray:
|
| 228 |
+
"""Preprocess image untuk ONNX inference dengan optimasi memory"""
|
| 229 |
+
image = Image.open(io.BytesIO(image_bytes)).convert('RGB')
|
| 230 |
+
image_np = np.array(image)
|
| 231 |
+
h, w, _ = image_np.shape
|
| 232 |
+
|
| 233 |
+
scale = min(input_size / w, input_size / h)
|
| 234 |
+
new_w, new_h = int(w * scale), int(h * scale)
|
| 235 |
+
|
| 236 |
+
resized_image = cv2.resize(image_np, (new_w, new_h))
|
| 237 |
+
padded_image = np.full((input_size, input_size, 3), 114, dtype=np.uint8)
|
| 238 |
+
|
| 239 |
+
# Calculate padding
|
| 240 |
+
y_offset = (input_size - new_h) // 2
|
| 241 |
+
x_offset = (input_size - new_w) // 2
|
| 242 |
+
|
| 243 |
+
padded_image[y_offset:y_offset + new_h, x_offset:x_offset + new_w, :] = resized_image
|
| 244 |
+
|
| 245 |
+
# Convert untuk ONNX
|
| 246 |
+
input_tensor = padded_image.astype(np.float32) / 255.0
|
| 247 |
+
input_tensor = np.transpose(input_tensor, (2, 0, 1))
|
| 248 |
+
input_tensor = np.expand_dims(input_tensor, axis=0)
|
| 249 |
+
|
| 250 |
+
return input_tensor
|
| 251 |
+
|
| 252 |
+
def fuzzy_match_label(target_label: str, class_names: List[str], threshold: float = 0.6) -> Optional[str]:
|
| 253 |
+
"""Fuzzy matching untuk label variations"""
|
| 254 |
+
target_normalized = target_label.lower().strip()
|
| 255 |
+
|
| 256 |
+
# Dictionary untuk common variations
|
| 257 |
+
label_variants = {
|
| 258 |
+
'ice cream': ['ice cream', 'icecream', 'ice'],
|
| 259 |
+
'hotdog': ['hot dog', 'hotdog', 'hot-dog'],
|
| 260 |
+
'hot dog': ['hot dog', 'hotdog', 'hot-dog'],
|
| 261 |
+
'sunglasses': ['sunglasses', 'sun glasses', 'sunglass'],
|
| 262 |
+
'sun glasses': ['sunglasses', 'sun glasses', 'sunglass']
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
# 1. Exact match
|
| 266 |
+
if target_normalized in class_names:
|
| 267 |
+
return target_normalized
|
| 268 |
+
|
| 269 |
+
# 2. Check known variants
|
| 270 |
+
for main_label, variants in label_variants.items():
|
| 271 |
+
if target_normalized in variants and main_label in class_names:
|
| 272 |
+
return main_label
|
| 273 |
+
|
| 274 |
+
# 3. Fuzzy matching
|
| 275 |
+
best_matches = difflib.get_close_matches(
|
| 276 |
+
target_normalized,
|
| 277 |
+
[name.lower() for name in class_names],
|
| 278 |
+
n=3,
|
| 279 |
+
cutoff=threshold
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
if best_matches:
|
| 283 |
+
for match in best_matches:
|
| 284 |
+
for class_name in class_names:
|
| 285 |
+
if class_name.lower() == match:
|
| 286 |
+
return class_name
|
| 287 |
+
|
| 288 |
+
# 4. Partial matching
|
| 289 |
+
for class_name in class_names:
|
| 290 |
+
if target_normalized in class_name.lower() or class_name.lower() in target_normalized:
|
| 291 |
+
return class_name
|
| 292 |
+
|
| 293 |
+
return None
|
| 294 |
+
|
| 295 |
+
def get_config_key_for_label(target_label: str) -> str:
|
| 296 |
+
"""Determine which model config to use"""
|
| 297 |
+
for keywords, config_key in MODEL_ROUTING:
|
| 298 |
+
if any(keyword in target_label for keyword in keywords):
|
| 299 |
+
return config_key
|
| 300 |
+
return 'default'
|
| 301 |
+
|
| 302 |
+
def get_button_index(x_center: float, y_center: float, img_width: int, img_height: int,
|
| 303 |
+
grid_cols: int = 3, grid_rows: int = 2) -> int:
|
| 304 |
+
"""Calculate button index dari coordinates"""
|
| 305 |
+
|
| 306 |
+
# Calculate grid cell dimensions
|
| 307 |
+
cell_width = img_width / grid_cols
|
| 308 |
+
cell_height = img_height / grid_rows
|
| 309 |
+
|
| 310 |
+
# Calculate which cell the center point falls into
|
| 311 |
+
col = int(x_center // cell_width)
|
| 312 |
+
row = int(y_center // cell_height)
|
| 313 |
+
|
| 314 |
+
# Ensure col and row are within bounds
|
| 315 |
+
col = max(0, min(col, grid_cols - 1))
|
| 316 |
+
row = max(0, min(row, grid_rows - 1))
|
| 317 |
+
|
| 318 |
+
# Calculate button index (1-based)
|
| 319 |
+
button_index = row * grid_cols + col + 1
|
| 320 |
+
|
| 321 |
+
# Debug logging
|
| 322 |
+
logger.info(f"π BUTTON INDEX DEBUG: Input coordinates: ({x_center:.2f}, {y_center:.2f})")
|
| 323 |
+
logger.info(f"π BUTTON INDEX DEBUG: Image dimensions: {img_width}x{img_height}")
|
| 324 |
+
logger.info(f"π BUTTON INDEX DEBUG: Grid: {grid_cols}x{grid_rows}")
|
| 325 |
+
logger.info(f"π BUTTON INDEX DEBUG: Cell dimensions: {cell_width:.2f}x{cell_height:.2f}")
|
| 326 |
+
logger.info(f"π BUTTON INDEX DEBUG: Grid position: col={col}, row={row}")
|
| 327 |
+
logger.info(f"π BUTTON INDEX DEBUG: Calculated button index: {button_index}")
|
| 328 |
+
logger.info(f"π BUTTON INDEX DEBUG: Grid layout visualization:")
|
| 329 |
+
logger.info(f"π BUTTON INDEX DEBUG: [1] [2] [3]")
|
| 330 |
+
logger.info(f"π BUTTON INDEX DEBUG: [4] [5] [6]")
|
| 331 |
+
logger.info(f"π BUTTON INDEX DEBUG: X ranges: [0-{cell_width:.1f}] [{cell_width:.1f}-{cell_width*2:.1f}] [{cell_width*2:.1f}-{img_width}]")
|
| 332 |
+
logger.info(f"π BUTTON INDEX DEBUG: Y ranges: [0-{cell_height:.1f}] [{cell_height:.1f}-{img_height}]")
|
| 333 |
+
|
| 334 |
+
return button_index
|
| 335 |
+
|
| 336 |
+
# =================================================================
|
| 337 |
+
# CACHING SYSTEM
|
| 338 |
+
# =================================================================
|
| 339 |
+
|
| 340 |
+
def get_cache_key(request_data: dict) -> str:
|
| 341 |
+
"""Generate cache key dari request data"""
|
| 342 |
+
cache_string = f"{request_data.get('challenge_type')}_{request_data.get('target_label')}_{request_data.get('image_b64', '')[:100]}"
|
| 343 |
+
return hashlib.md5(cache_string.encode()).hexdigest()
|
| 344 |
+
|
| 345 |
+
def get_cached_response(cache_key: str) -> Optional[dict]:
|
| 346 |
+
"""Get response dari cache jika ada"""
|
| 347 |
+
return RESPONSE_CACHE.get(cache_key)
|
| 348 |
+
|
| 349 |
+
def cache_response(cache_key: str, response: dict):
|
| 350 |
+
"""Cache response dengan size limit"""
|
| 351 |
+
if len(RESPONSE_CACHE) >= CACHE_MAX_SIZE:
|
| 352 |
+
# Remove oldest entry
|
| 353 |
+
oldest_key = next(iter(RESPONSE_CACHE))
|
| 354 |
+
del RESPONSE_CACHE[oldest_key]
|
| 355 |
+
|
| 356 |
+
RESPONSE_CACHE[cache_key] = response
|
| 357 |
+
|
| 358 |
+
# =================================================================
|
| 359 |
+
# CHALLENGE HANDLERS
|
| 360 |
+
# =================================================================
|
| 361 |
+
|
| 362 |
+
async def handle_pick_the_challenge(data: dict) -> dict:
|
| 363 |
+
"""Handle 'pick the' challenges dengan fuzzy matching"""
|
| 364 |
+
start_time = datetime.now()
|
| 365 |
+
|
| 366 |
+
target_label_original = data['target_label']
|
| 367 |
+
image_b64 = data['image_b64']
|
| 368 |
+
target_label = target_label_original
|
| 369 |
+
|
| 370 |
+
config_key = get_config_key_for_label(target_label)
|
| 371 |
+
|
| 372 |
+
if config_key == 'spiral_galaxy':
|
| 373 |
+
target_label = 'spiral'
|
| 374 |
+
|
| 375 |
+
model_data = await ModelManager.get_model(config_key)
|
| 376 |
+
if not model_data:
|
| 377 |
+
if not ML_BACKEND_AVAILABLE:
|
| 378 |
+
return {
|
| 379 |
+
'status': 'error',
|
| 380 |
+
'message': 'No ML backend available - model inference disabled',
|
| 381 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 382 |
+
}
|
| 383 |
+
return {
|
| 384 |
+
'status': 'error',
|
| 385 |
+
'message': f'Model {config_key} tidak ditemukan',
|
| 386 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
try:
|
| 390 |
+
# Decode image
|
| 391 |
+
image_bytes = base64.b64decode(image_b64.split(',')[1])
|
| 392 |
+
|
| 393 |
+
# Fuzzy matching untuk label
|
| 394 |
+
matched_label = fuzzy_match_label(target_label, model_data['class_names'])
|
| 395 |
+
if not matched_label:
|
| 396 |
+
return {
|
| 397 |
+
'status': 'not_found',
|
| 398 |
+
'message': f'Label "{target_label}" tidak ditemukan dalam model',
|
| 399 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
target_label = matched_label
|
| 403 |
+
|
| 404 |
+
# Preprocessing
|
| 405 |
+
input_tensor = preprocess_image(image_bytes, model_data['input_size'])
|
| 406 |
+
|
| 407 |
+
# Inference
|
| 408 |
+
outputs = model_data['session'].run(None, {model_data['input_name']: input_tensor})[0]
|
| 409 |
+
predictions = np.squeeze(outputs).T
|
| 410 |
+
|
| 411 |
+
# Process detections
|
| 412 |
+
boxes = []
|
| 413 |
+
confidences = []
|
| 414 |
+
class_ids = []
|
| 415 |
+
|
| 416 |
+
for pred in predictions:
|
| 417 |
+
class_scores = pred[4:]
|
| 418 |
+
class_id = np.argmax(class_scores)
|
| 419 |
+
max_confidence = class_scores[class_id]
|
| 420 |
+
|
| 421 |
+
if max_confidence > model_data['confidence']:
|
| 422 |
+
confidences.append(float(max_confidence))
|
| 423 |
+
class_ids.append(class_id)
|
| 424 |
+
box_model = pred[:4]
|
| 425 |
+
x_center, y_center, width, height = box_model
|
| 426 |
+
x1 = x_center - width / 2
|
| 427 |
+
y1 = y_center - height / 2
|
| 428 |
+
boxes.append([int(x1), int(y1), int(width), int(height)])
|
| 429 |
+
|
| 430 |
+
if not boxes:
|
| 431 |
+
return {
|
| 432 |
+
'status': 'not_found',
|
| 433 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
# Non-Maximum Suppression
|
| 437 |
+
indices = cv2.dnn.NMSBoxes(
|
| 438 |
+
np.array(boxes),
|
| 439 |
+
np.array(confidences),
|
| 440 |
+
model_data['confidence'],
|
| 441 |
+
model_data['nms']
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
if len(indices) == 0:
|
| 445 |
+
return {
|
| 446 |
+
'status': 'not_found',
|
| 447 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
# Find target
|
| 451 |
+
target_class_id = model_data['class_names'].index(target_label)
|
| 452 |
+
best_match_box = None
|
| 453 |
+
highest_score = 0
|
| 454 |
+
|
| 455 |
+
for i in indices.flatten():
|
| 456 |
+
if class_ids[i] == target_class_id:
|
| 457 |
+
current_score = confidences[i]
|
| 458 |
+
if current_score > highest_score:
|
| 459 |
+
highest_score = current_score
|
| 460 |
+
best_match_box = boxes[i]
|
| 461 |
+
|
| 462 |
+
if best_match_box is not None:
|
| 463 |
+
# Scale back to original coordinates
|
| 464 |
+
img = Image.open(io.BytesIO(image_bytes))
|
| 465 |
+
original_w, original_h = img.size
|
| 466 |
+
scale = min(model_data['input_size'] / original_w, model_data['input_size'] / original_h)
|
| 467 |
+
pad_x = (model_data['input_size'] - original_w * scale) / 2
|
| 468 |
+
pad_y = (model_data['input_size'] - original_h * scale) / 2
|
| 469 |
+
|
| 470 |
+
x_orig = (best_match_box[0] - pad_x) / scale
|
| 471 |
+
y_orig = (best_match_box[1] - pad_y) / scale
|
| 472 |
+
w_orig = best_match_box[2] / scale
|
| 473 |
+
h_orig = best_match_box[3] / scale
|
| 474 |
+
|
| 475 |
+
return {
|
| 476 |
+
'status': 'success',
|
| 477 |
+
'box': [x_orig, y_orig, w_orig, h_orig],
|
| 478 |
+
'confidence': highest_score,
|
| 479 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
except Exception as e:
|
| 483 |
+
logger.error(f"Error in handle_pick_the_challenge: {e}")
|
| 484 |
+
return {
|
| 485 |
+
'status': 'error',
|
| 486 |
+
'message': str(e),
|
| 487 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
return {
|
| 491 |
+
'status': 'not_found',
|
| 492 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
async def handle_upright_challenge(data: dict) -> dict:
|
| 496 |
+
"""Handle 'upright' challenges"""
|
| 497 |
+
start_time = datetime.now()
|
| 498 |
+
|
| 499 |
+
try:
|
| 500 |
+
image_b64 = data['image_b64']
|
| 501 |
+
model_data = await ModelManager.get_model('upright')
|
| 502 |
+
|
| 503 |
+
if not model_data:
|
| 504 |
+
if not ML_BACKEND_AVAILABLE:
|
| 505 |
+
return {
|
| 506 |
+
'status': 'error',
|
| 507 |
+
'message': 'No ML backend available - model inference disabled',
|
| 508 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 509 |
+
}
|
| 510 |
+
return {
|
| 511 |
+
'status': 'error',
|
| 512 |
+
'message': 'Model upright tidak ditemukan',
|
| 513 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
image_bytes = base64.b64decode(image_b64.split(',')[1])
|
| 517 |
+
reconstructed_image_pil = Image.open(io.BytesIO(image_bytes))
|
| 518 |
+
original_w, original_h = reconstructed_image_pil.size
|
| 519 |
+
|
| 520 |
+
# Debug: Log image dimensions
|
| 521 |
+
logger.info(f"π UPRIGHT DEBUG: Original image dimensions: {original_w}x{original_h}")
|
| 522 |
+
|
| 523 |
+
input_tensor = preprocess_image(image_bytes, model_data['input_size'])
|
| 524 |
+
outputs = model_data['session'].run(None, {model_data['input_name']: input_tensor})[0]
|
| 525 |
+
|
| 526 |
+
predictions = np.squeeze(outputs).T
|
| 527 |
+
confident_preds = predictions[predictions[:, 4] > model_data['confidence']]
|
| 528 |
+
|
| 529 |
+
# Debug: Log predictions info
|
| 530 |
+
logger.info(f"π UPRIGHT DEBUG: Total predictions: {len(predictions)}, Confident predictions: {len(confident_preds)}")
|
| 531 |
+
logger.info(f"π UPRIGHT DEBUG: Confidence threshold: {model_data['confidence']}")
|
| 532 |
+
|
| 533 |
+
if len(confident_preds) == 0:
|
| 534 |
+
return {
|
| 535 |
+
'status': 'not_found',
|
| 536 |
+
'message': 'Tidak ada objek terdeteksi',
|
| 537 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 538 |
+
}
|
| 539 |
+
|
| 540 |
+
# Debug: Log all confident predictions
|
| 541 |
+
for i, pred in enumerate(confident_preds):
|
| 542 |
+
logger.info(f"π UPRIGHT DEBUG: Prediction {i+1}: x_center={pred[0]:.2f}, y_center={pred[1]:.2f}, width={pred[2]:.2f}, height={pred[3]:.2f}, confidence={pred[4]:.4f}")
|
| 543 |
+
|
| 544 |
+
best_detection = confident_preds[np.argmax(confident_preds[:, 4])]
|
| 545 |
+
box_model = best_detection[:4]
|
| 546 |
+
|
| 547 |
+
# Debug: Log model space coordinates
|
| 548 |
+
logger.info(f"π UPRIGHT DEBUG: Best detection (model space): x_center={box_model[0]:.2f}, y_center={box_model[1]:.2f}, width={box_model[2]:.2f}, height={box_model[3]:.2f}")
|
| 549 |
+
|
| 550 |
+
scale = min(model_data['input_size'] / original_w, model_data['input_size'] / original_h)
|
| 551 |
+
pad_x = (model_data['input_size'] - original_w * scale) / 2
|
| 552 |
+
pad_y = (model_data['input_size'] - original_h * scale) / 2
|
| 553 |
+
|
| 554 |
+
# Debug: Log scaling parameters
|
| 555 |
+
logger.info(f"π UPRIGHT DEBUG: Scaling parameters: scale={scale:.4f}, pad_x={pad_x:.2f}, pad_y={pad_y:.2f}")
|
| 556 |
+
logger.info(f"π UPRIGHT DEBUG: Model input size: {model_data['input_size']}")
|
| 557 |
+
|
| 558 |
+
x_center_orig = (box_model[0] - pad_x) / scale
|
| 559 |
+
y_center_orig = (box_model[1] - pad_y) / scale
|
| 560 |
+
|
| 561 |
+
# Debug: Log original space coordinates
|
| 562 |
+
logger.info(f"π UPRIGHT DEBUG: Original space coordinates: x_center={x_center_orig:.2f}, y_center={y_center_orig:.2f}")
|
| 563 |
+
|
| 564 |
+
# Debug: Log grid calculation details
|
| 565 |
+
grid_cols, grid_rows = 3, 2
|
| 566 |
+
col = int(x_center_orig // (original_w / grid_cols))
|
| 567 |
+
row = int(y_center_orig // (original_h / grid_rows))
|
| 568 |
+
logger.info(f"π UPRIGHT DEBUG: Grid calculation: grid_cols={grid_cols}, grid_rows={grid_rows}")
|
| 569 |
+
logger.info(f"π UPRIGHT DEBUG: Cell calculation: col={col}, row={row}")
|
| 570 |
+
logger.info(f"π UPRIGHT DEBUG: Grid cell dimensions: width={original_w/grid_cols:.2f}, height={original_h/grid_rows:.2f}")
|
| 571 |
+
|
| 572 |
+
button_to_click = get_button_index(x_center_orig, y_center_orig, original_w, original_h)
|
| 573 |
+
|
| 574 |
+
# Debug: Log final result
|
| 575 |
+
logger.info(f"π UPRIGHT DEBUG: Final button index: {button_to_click}")
|
| 576 |
+
logger.info(f"π UPRIGHT DEBUG: Button layout (3x2 grid): [1, 2, 3] [4, 5, 6]")
|
| 577 |
+
|
| 578 |
+
return {
|
| 579 |
+
'status': 'success',
|
| 580 |
+
'button_index': button_to_click,
|
| 581 |
+
'confidence': float(best_detection[4]),
|
| 582 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 583 |
+
}
|
| 584 |
+
|
| 585 |
+
except Exception as e:
|
| 586 |
+
logger.error(f"Error in handle_upright_challenge: {e}")
|
| 587 |
+
return {
|
| 588 |
+
'status': 'error',
|
| 589 |
+
'message': str(e),
|
| 590 |
+
'processing_time': (datetime.now() - start_time).total_seconds()
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
# =================================================================
|
| 594 |
+
# FASTAPI APPLICATION
|
| 595 |
+
# =================================================================
|
| 596 |
+
|
| 597 |
+
app = FastAPI(
|
| 598 |
+
title="π§© FunCaptcha Solver API",
|
| 599 |
+
description="High-performance FunCaptcha solver dengan fuzzy matching untuk Hugging Face Spaces",
|
| 600 |
+
version="1.0.0",
|
| 601 |
+
docs_url="/docs",
|
| 602 |
+
redoc_url="/redoc"
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
# CORS middleware
|
| 606 |
+
app.add_middleware(
|
| 607 |
+
CORSMiddleware,
|
| 608 |
+
allow_origins=["*"],
|
| 609 |
+
allow_credentials=True,
|
| 610 |
+
allow_methods=["*"],
|
| 611 |
+
allow_headers=["*"],
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
@app.get("/")
|
| 615 |
+
async def root():
|
| 616 |
+
"""Root endpoint dengan info API"""
|
| 617 |
+
return {
|
| 618 |
+
"service": "FunCaptcha Solver API",
|
| 619 |
+
"version": "1.0.0",
|
| 620 |
+
"status": "running",
|
| 621 |
+
"endpoints": {
|
| 622 |
+
"/solve": "POST - Solve FunCaptcha challenges",
|
| 623 |
+
"/health": "GET - Health check",
|
| 624 |
+
"/docs": "GET - API documentation"
|
| 625 |
+
},
|
| 626 |
+
"models_loaded": len(LOADED_MODELS),
|
| 627 |
+
"cache_size": len(RESPONSE_CACHE)
|
| 628 |
+
}
|
| 629 |
+
|
| 630 |
+
@app.get("/health")
|
| 631 |
+
async def health_check():
|
| 632 |
+
"""Health check endpoint"""
|
| 633 |
+
warnings = []
|
| 634 |
+
if not ONNX_AVAILABLE:
|
| 635 |
+
warnings.append("ONNX Runtime not available")
|
| 636 |
+
if not ML_BACKEND_AVAILABLE:
|
| 637 |
+
warnings.append("No ML backend available - model inference disabled")
|
| 638 |
+
|
| 639 |
+
backend_status = "none"
|
| 640 |
+
if ONNX_AVAILABLE:
|
| 641 |
+
backend_status = "onnxruntime"
|
| 642 |
+
elif TORCH_AVAILABLE:
|
| 643 |
+
backend_status = "pytorch"
|
| 644 |
+
elif TF_AVAILABLE:
|
| 645 |
+
backend_status = "tensorflow"
|
| 646 |
+
|
| 647 |
+
return {
|
| 648 |
+
"status": "healthy" if ML_BACKEND_AVAILABLE else "degraded",
|
| 649 |
+
"service": "FunCaptcha Solver",
|
| 650 |
+
"ml_backend": backend_status,
|
| 651 |
+
"onnx_runtime_available": ONNX_AVAILABLE,
|
| 652 |
+
"pytorch_available": TORCH_AVAILABLE,
|
| 653 |
+
"tensorflow_available": TF_AVAILABLE,
|
| 654 |
+
"models_loaded": len(LOADED_MODELS),
|
| 655 |
+
"available_models": list(CONFIGS.keys()),
|
| 656 |
+
"cache_entries": len(RESPONSE_CACHE),
|
| 657 |
+
"warnings": warnings
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
@app.post("/solve", response_model=FunCaptchaResponse)
|
| 661 |
+
async def solve_funcaptcha(
|
| 662 |
+
request: FunCaptchaRequest,
|
| 663 |
+
authenticated: bool = Depends(verify_api_key)
|
| 664 |
+
) -> FunCaptchaResponse:
|
| 665 |
+
"""
|
| 666 |
+
π§© Solve FunCaptcha challenges
|
| 667 |
+
|
| 668 |
+
Supports:
|
| 669 |
+
- pick_the: Pick specific objects dari images
|
| 670 |
+
- upright: Find correctly oriented objects
|
| 671 |
+
|
| 672 |
+
Features:
|
| 673 |
+
- Fuzzy label matching
|
| 674 |
+
- Response caching
|
| 675 |
+
- Multi-model support
|
| 676 |
+
"""
|
| 677 |
+
|
| 678 |
+
# Generate cache key
|
| 679 |
+
request_dict = request.dict()
|
| 680 |
+
cache_key = get_cache_key(request_dict)
|
| 681 |
+
|
| 682 |
+
# Check cache first
|
| 683 |
+
cached_response = get_cached_response(cache_key)
|
| 684 |
+
if cached_response:
|
| 685 |
+
logger.info(f"Cache hit for challenge: {request.challenge_type}")
|
| 686 |
+
return FunCaptchaResponse(**cached_response)
|
| 687 |
+
|
| 688 |
+
# Process request
|
| 689 |
+
if request.challenge_type == 'pick_the':
|
| 690 |
+
if not request.target_label:
|
| 691 |
+
raise HTTPException(status_code=400, detail="target_label required for pick_the challenges")
|
| 692 |
+
result = await handle_pick_the_challenge(request_dict)
|
| 693 |
+
elif request.challenge_type == 'upright':
|
| 694 |
+
result = await handle_upright_challenge(request_dict)
|
| 695 |
+
else:
|
| 696 |
+
raise HTTPException(status_code=400, detail=f"Unsupported challenge type: {request.challenge_type}")
|
| 697 |
+
|
| 698 |
+
# Cache response
|
| 699 |
+
cache_response(cache_key, result)
|
| 700 |
+
|
| 701 |
+
logger.info(f"Challenge solved: {request.challenge_type} -> {result['status']}")
|
| 702 |
+
|
| 703 |
+
return FunCaptchaResponse(**result)
|
| 704 |
+
|
| 705 |
+
# =================================================================
|
| 706 |
+
# APPLICATION STARTUP
|
| 707 |
+
# =================================================================
|
| 708 |
+
|
| 709 |
+
@app.on_event("startup")
|
| 710 |
+
async def startup_event():
|
| 711 |
+
"""Initialize aplikasi saat startup"""
|
| 712 |
+
logger.info("π Starting FunCaptcha Solver API...")
|
| 713 |
+
|
| 714 |
+
# Verify API key ada
|
| 715 |
+
try:
|
| 716 |
+
api_key = get_api_key_from_secrets()
|
| 717 |
+
logger.info("β
API key loaded successfully")
|
| 718 |
+
except ValueError as e:
|
| 719 |
+
logger.error(f"β API key error: {e}")
|
| 720 |
+
raise e
|
| 721 |
+
|
| 722 |
+
# Preload default model jika ada dan ML backend available
|
| 723 |
+
if ML_BACKEND_AVAILABLE and os.path.exists('best.onnx') and os.path.exists('data.yaml'):
|
| 724 |
+
logger.info("Preloading default model...")
|
| 725 |
+
try:
|
| 726 |
+
await ModelManager.get_model('default')
|
| 727 |
+
logger.info("β
Default model preloaded successfully")
|
| 728 |
+
except Exception as e:
|
| 729 |
+
logger.warning(f"β οΈ Failed to preload default model: {e}")
|
| 730 |
+
elif not ML_BACKEND_AVAILABLE:
|
| 731 |
+
logger.warning("β οΈ No ML backend available - skipping model preload")
|
| 732 |
+
else:
|
| 733 |
+
logger.warning("β οΈ Model files (best.onnx, data.yaml) not found - upload them to enable solving")
|
| 734 |
+
|
| 735 |
+
if ML_BACKEND_AVAILABLE:
|
| 736 |
+
backend_name = "ONNX Runtime" if ONNX_AVAILABLE else "PyTorch" if TORCH_AVAILABLE else "TensorFlow"
|
| 737 |
+
logger.info(f"β
FunCaptcha Solver API started successfully with {backend_name} backend")
|
| 738 |
+
else:
|
| 739 |
+
logger.warning("β οΈ FunCaptcha Solver API started with limited functionality (No ML backend available)")
|
| 740 |
+
|
| 741 |
+
@app.on_event("shutdown")
|
| 742 |
+
async def shutdown_event():
|
| 743 |
+
"""Cleanup saat shutdown"""
|
| 744 |
+
logger.info("π Shutting down FunCaptcha Solver API...")
|
| 745 |
+
|
| 746 |
+
# Clear caches
|
| 747 |
+
LOADED_MODELS.clear()
|
| 748 |
+
RESPONSE_CACHE.clear()
|
| 749 |
+
|
| 750 |
+
logger.info("β
Cleanup completed")
|
| 751 |
+
|
| 752 |
+
# =================================================================
|
| 753 |
+
# DEVELOPMENT SERVER
|
| 754 |
+
# =================================================================
|
| 755 |
+
|
| 756 |
+
if __name__ == "__main__":
|
| 757 |
+
uvicorn.run(
|
| 758 |
+
"app:app",
|
| 759 |
+
host="0.0.0.0",
|
| 760 |
+
port=7860,
|
| 761 |
+
reload=False, # Disabled untuk production
|
| 762 |
+
workers=1 # Single worker untuk HF Spaces
|
| 763 |
+
)
|