File size: 7,471 Bytes
603a5b3
 
 
 
 
 
 
 
 
 
 
1291bc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
---

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](https://huggingface.co/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**:

```bash

# 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

```json

{

  "challenge_type": "pick_the",

  "image_b64": "data:image/png;base64,iVBORw0KGgo...",

  "target_label": "ice cream"

}

```

### Response Format

```json

{

  "status": "success",

  "box": [120.5, 80.3, 150.0, 100.0],

  "confidence": 0.89,

  "processing_time": 0.245,

  "message": null

}

```

## πŸ§ͺ Testing

### Local Testing

```bash

# 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

```python

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:

```python

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

```bash

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:

```python

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:

```javascript

// funcaptcha-blob-fixed.js

const SOLVER_SERVER_URL = 'https://your-space-url.hf.space/solve';

const API_KEY = 'your-api-key-here';

```