funcaptcha / README.md
doniramdani820's picture
Upload 5 files
603a5b3 verified
metadata
title: FunCaptcha Solver API
emoji: 🧩
colorFrom: blue
colorTo: purple
sdk: docker
pinned: false
suggested_hardware: cpu-basic
app_file: app.py

🧩 FunCaptcha Solver API - Hugging Face Spaces

High-performance FunCaptcha solver dengan fuzzy matching dan API key authentication

πŸš€ Features

  • βœ… FastAPI - High performance async web framework
  • βœ… Docker optimization - Multi-stage build untuk size minimal
  • βœ… Fuzzy label matching - Handle variasi label seperti "ice cream" vs "ice"
  • βœ… API key authentication - Secure access menggunakan HF Secrets
  • βœ… Response caching - Fast responses untuk requests yang sama
  • βœ… Multi-model support - Support berbagai jenis CAPTCHA challenges
  • βœ… Memory efficient - Optimized untuk HF Spaces environment
  • βœ… Auto health checks - Built-in monitoring

πŸ“‹ Supported Challenge Types

Challenge Type Description Response
pick_the Pick specific objects dari images {status, box, confidence}
upright Find correctly oriented objects {status, button_index, confidence}

πŸ”§ Deployment ke Hugging Face Spaces

1. Create New Space

  1. Buka Hugging Face Spaces
  2. Click "Create new Space"
  3. Pilih:
    • Space name: funcaptcha-solver-api (atau nama pilihan Anda)
    • License: mit
    • Space SDK: Docker
    • Space visibility: Private (recommended)

2. Upload Files

Upload semua files dalam folder ini ke Space repository:

hf-funcaptcha-deployment/
β”œβ”€β”€ Dockerfile              # Docker configuration
β”œβ”€β”€ app.py                  # Main FastAPI application  
β”œβ”€β”€ requirements.txt        # Python dependencies
β”œβ”€β”€ README.md              # Documentation (this file)
β”œβ”€β”€ data.yaml              # Class names untuk default model
β”œβ”€β”€ best.onnx              # ONNX model file (upload manually)
└── test-api.py           # Testing script

3. Setup API Key (CRITICAL!)

  1. Di Space settings, buka tab "Settings"
  2. Scroll ke "Repository secrets"
  3. Add new secret:
    • Name: FUNCAPTCHA_API_KEY
    • Value: your-secure-api-key-here (generate strong key)

⚠️ PENTING: Tanpa API key, aplikasi tidak akan start!

4. Upload Model Files

Upload model files ke Space repository:

  • best.onnx - Main detection model
  • data.yaml - Class names configuration
  • bestspiral.onnx (optional) - Spiral galaxy model
  • dataspiral.yaml (optional) - Spiral galaxy classes
  • best_Upright.onnx (optional) - Upright detection model
  • data_upright.yaml (optional) - Upright detection classes

5. Deploy & Test

  1. Space akan auto-deploy setelah files uploaded
  2. Wait untuk build process selesai (~5-10 minutes)
  3. Test endpoint: https://your-space-url.hf.space/health

πŸ”‘ Authentication

Semua API endpoints require Bearer token authentication:

# Example request
curl -X POST "https://your-space-url.hf.space/solve" \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "challenge_type": "pick_the",
    "image_b64": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...",
    "target_label": "ice cream"
  }'

πŸ“ API Documentation

Endpoints

Endpoint Method Description Auth Required
/ GET Root info & status ❌
/health GET Health check ❌
/solve POST Solve FunCaptcha βœ…
/docs GET Interactive API docs ❌

Request Format

{
  "challenge_type": "pick_the",
  "image_b64": "data:image/png;base64,iVBORw0KGgo...",
  "target_label": "ice cream"
}

Response Format

{
  "status": "success",
  "box": [120.5, 80.3, 150.0, 100.0],
  "confidence": 0.89,
  "processing_time": 0.245,
  "message": null
}

πŸ§ͺ Testing

Local Testing

# Install dependencies
pip install -r requirements.txt

# Set API key
export FUNCAPTCHA_API_KEY="your-test-key"

# Run server
python app.py

# Test with provided script
python test-api.py

Production Testing

import requests
import base64

# Load test image
with open("test_image.png", "rb") as f:
    image_b64 = base64.b64encode(f.read()).decode()

# Make request
response = requests.post(
    "https://your-space-url.hf.space/solve",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "challenge_type": "pick_the", 
        "image_b64": f"data:image/png;base64,{image_b64}",
        "target_label": "ice cream"
    }
)

print(response.json())

βš™οΈ Configuration

Model Configuration

Edit CONFIGS in app.py untuk custom models:

CONFIGS = {
    'default': {
        'model_path': 'best.onnx',
        'yaml_path': 'data.yaml', 
        'input_size': 640,
        'confidence_threshold': 0.4,
        'nms_threshold': 0.2
    }
    # Add more models...
}

Environment Variables

Variable Description Required
FUNCAPTCHA_API_KEY API key untuk authentication βœ…
OMP_NUM_THREADS CPU threads untuk optimization ❌ (default: 2)
CACHE_MAX_SIZE Maximum cache entries ❌ (default: 100)

πŸ” Monitoring & Debugging

Health Check

curl https://your-space-url.hf.space/health

Logs

  • Check HF Spaces logs dalam space interface
  • Logs include processing times, cache hits, errors

Performance Metrics

  • Processing time: Biasanya < 300ms per request
  • Memory usage: ~500MB dengan 1 model loaded
  • Cache hit rate: Displayed in /health endpoint

🚨 Troubleshooting

Common Issues

  1. "API key not found"

    • Solution: Set FUNCAPTCHA_API_KEY di Space secrets
  2. "Model file not found"

    • Solution: Upload model files (.onnx, .yaml) ke repository
  3. "401 Unauthorized"

    • Solution: Check API key dalam request header
  4. Slow responses

    • Check: Model loading, enable caching
    • Monitor: Memory usage dalam Space logs

Debug Mode

Untuk debugging, set logging level:

import logging
logging.basicConfig(level=logging.DEBUG)

πŸ“Š Performance Optimization

  • βœ… Model caching - Models loaded once, reused
  • βœ… Response caching - Identical requests cached
  • βœ… CPU optimization - ONNX dengan CPU-specific settings
  • βœ… Memory efficiency - Minimal memory footprint
  • βœ… Async operations - Non-blocking request handling

πŸ” Security

  • βœ… API key authentication via Bearer tokens
  • βœ… CORS protection configured
  • βœ… Input validation dengan Pydantic models
  • βœ… Error handling tanpa expose internal details

πŸ“ž Support

  • Issues: Report dalam repository issues
  • Updates: Check Space status dan rebuild jika needed
  • Performance: Monitor via /health endpoint

🎯 Ready to deploy? Upload files, set API key, dan Space siap digunakan!

🌐 Client Integration

Update client untuk menggunakan Space URL:

// funcaptcha-blob-fixed.js
const SOLVER_SERVER_URL = 'https://your-space-url.hf.space/solve';
const API_KEY = 'your-api-key-here';