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
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
# πŸ”§ Python API Troubleshooting Guide

Panduan mengatasi error umum di Python API.

## ❌ Error: "No module named 'sklearn'"

### Problem
```
Error loading model: No module named 'sklearn'
```

### Penyebab
scikit-learn belum terinstall atau nama import tidak sesuai.

### Solusi

**Option 1: Reinstall scikit-learn**
```bash
pip uninstall scikit-learn -y
pip install scikit-learn==1.3.2
```

**Option 2: Install semua dependencies ulang**
```bash
cd python-api
pip install -r requirements.txt
```

**Option 3: Gunakan virtual environment (Recommended)**
```bash
# Windows
python -m venv venv
venv\Scripts\activate
pip install -r requirements.txt

# Linux/Mac
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```

### Verifikasi
```bash
python -c "import sklearn; print(sklearn.__version__)"
# Output: 1.3.2
```

---

## ⚠️ Warning: "Supabase credentials not found"

### Problem
```
⚠ Supabase credentials not found, predictions won't be saved to database
```

### Penyebab
File `.env` tidak ada atau environment variables tidak diset.

### Solusi

**1. Buat file .env**
```bash
cd python-api
copy .env.example .env  # Windows
# atau
cp .env.example .env    # Linux/Mac
```

**2. Edit .env dengan credentials yang benar:**
```env
SUPABASE_URL=https://xyddxrfiacdcnipdclas.supabase.co
SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

**3. Restart server:**
```bash
python app.py
```

### Expected Output
```
βœ… Supabase client initialized successfully
βœ… Model loaded successfully
```

---

## 🚫 Error: "FileNotFoundError: models/svm_densenet201_rbf.joblib"

### Problem
```
FileNotFoundError: [Errno 2] No such file or directory: 'models/svm_densenet201_rbf.joblib'
```

### Penyebab
Model files belum ada di folder `python-api/models/`.

### Solusi

**1. Download model files dari Google Drive**
- `svm_densenet201_rbf.joblib` (5.2 MB)
- `metadata.json` (353 bytes)

**2. Letakkan di folder yang benar:**
```
python-api/
β”œβ”€β”€ app.py
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ svm_densenet201_rbf.joblib  ← Di sini
β”‚   └── metadata.json               ← Di sini
└── requirements.txt
```

**3. Verify:**
```bash
# Windows
dir python-api\models

# Linux/Mac
ls -lh python-api/models/
```

πŸ“– **Panduan lengkap:** Lihat `CARA_MELETAKKAN_FILE_MODEL.md`

---

## 🌐 Error: CORS Issues

### Problem
```javascript
Access to fetch at 'http://localhost:5000/classify' from origin 'http://localhost:3000'
has been blocked by CORS policy
```

### Penyebab
CORS headers tidak dikonfigurasi dengan benar.

### Solusi

**1. Verify flask-cors terinstall:**
```bash
pip show flask-cors
```

**2. Check app.py line 15:**
```python
CORS(app)  # Pastikan ini ada
```

**3. Restart server**

### Verifikasi
```bash
curl -X OPTIONS http://localhost:5000/classify -v
# Harus ada header: Access-Control-Allow-Origin: *
```

---

## πŸ’Ύ Error: "Predictions not saving to database"

### Problem
API respond sukses tapi data tidak masuk Supabase.

### Penyebab
1. Environment variables tidak diset
2. RLS policies terlalu restrictive
3. Table schema tidak sesuai

### Solusi

**1. Check environment variables:**
```python
import os
print(os.getenv('SUPABASE_URL'))
print(os.getenv('SUPABASE_ANON_KEY'))
```

**2. Check Supabase RLS policies:**
```sql
-- Di Supabase SQL Editor
SELECT * FROM pg_policies WHERE tablename = 'predictions';
```

**3. Verify table structure:**
```sql
\d predictions
```

Expected columns:
- `id` (uuid, primary key)
- `image_data` (text)
- `predicted_class` (text)
- `confidence` (float8)
- `probabilities` (jsonb)
- `mode` (text)
- `created_at` (timestamptz)

**4. Test manual insert:**
```python
from supabase import create_client
import os

client = create_client(
    os.getenv('SUPABASE_URL'),
    os.getenv('SUPABASE_ANON_KEY')
)

result = client.table('predictions').insert({
    'image_data': 'test',
    'predicted_class': '6 Bulan',
    'confidence': 0.85,
    'probabilities': {'3 Bulan': 0.05, '6 Bulan': 0.85, '9 Bulan': 0.10},
    'mode': 'api'
}).execute()

print(result)
```

---

## πŸ”₯ Error: "torch.cuda.OutOfMemoryError"

### Problem
```
RuntimeError: CUDA out of memory
```

### Penyebab
GPU memory tidak cukup untuk load model.

### Solusi

**Option 1: Force CPU mode**

Edit `app.py`:
```python
# Line ~25
device = torch.device('cpu')  # Force CPU
print(f"Using device: {device}")
```

**Option 2: Reduce batch size**

Untuk production, gunakan Hugging Face Spaces dengan GPU atau Google Cloud Run.

---

## 🐌 Performance: API Too Slow

### Problem
Response time > 10 detik per request.

### Penyebab
1. Model reload setiap request
2. CPU-only inference
3. Large image size

### Solusi

**1. Model caching (Already implemented):**
```python
# app.py - Model loaded once saat startup
model = load_model()  # Global variable
```

**2. Image optimization:**
```python
# Resize sebelum send
max_size = 1024
if image.size[0] > max_size or image.size[1] > max_size:
    image.thumbnail((max_size, max_size))
```

**3. Deploy ke platform dengan GPU:**
- Hugging Face Spaces (T4 GPU gratis)
- Google Cloud Run (GPU available)
- Railway (CPU optimized)

---

## πŸ“¦ Error: "pip install failed"

### Problem
```
ERROR: Could not find a version that satisfies the requirement torch==2.1.0
```

### Penyebab
Python version atau platform tidak compatible.

### Solusi

**1. Check Python version:**
```bash
python --version
# Harus: Python 3.10.x atau 3.11.x
```

**2. Install torch dengan index URL:**
```bash
# CPU only
pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu

# Kemudian install sisanya
pip install -r requirements.txt
```

**3. Update pip:**
```bash
python -m pip install --upgrade pip
```

---

## πŸ”Œ Error: "Connection refused"

### Problem
```
ConnectionError: HTTPConnectionPool(host='localhost', port=5000):
Max retries exceeded with url: /classify
```

### Penyebab
1. Server tidak running
2. Port sudah dipakai
3. Firewall blocking

### Solusi

**1. Check server status:**
```bash
# Harus tampil: "Running on http://127.0.0.1:5000"
python app.py
```

**2. Check port:**
```bash
# Windows
netstat -ano | findstr :5000

# Linux/Mac
lsof -i :5000
```

**3. Gunakan port lain:**
```bash
# Di .env
PORT=5001
```

**4. Test dengan curl:**
```bash
curl http://localhost:5000/health
# Expected: {"status": "ok"}
```

---

## πŸ“ Logging & Debugging

### Enable Debug Mode

```python
# app.py
if __name__ == '__main__':
    app.run(
        host='0.0.0.0',
        port=int(os.getenv('PORT', 5000)),
        debug=True  # ← Set True untuk development
    )
```

### Check Logs

```bash
# Lihat full error trace
python app.py 2>&1 | tee api.log
```

### Test Endpoints

```bash
# Health check
curl http://localhost:5000/health

# Test classification
cd python-api
python test_local.py http://localhost:5000 test_image.jpg
```

---

## 🌍 Production Deployment Issues

### Hugging Face Spaces

**Problem:** Space status "Building" forever

**Solution:**
```dockerfile
# Verify Dockerfile
FROM python:3.10

WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt

EXPOSE 7860
CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--timeout", "120", "app:app"]
```

### Railway

**Problem:** "Module not found" di production tapi lokal OK

**Solution:**
```bash
# Pastikan requirements.txt complete
pip freeze > requirements.txt
```

### Environment Variables

**Problem:** Env vars tidak terbaca di production

**Solution:**
1. Set via platform dashboard (Railway/Hugging Face)
2. Jangan commit `.env` ke git
3. Verify dengan `/health` endpoint

---

## πŸ†˜ Masih Bermasalah?

### Langkah Debugging Sistematis

1. **Check Prerequisites:**
   ```bash
   python --version  # 3.10+
   pip list | grep -E "torch|sklearn|flask"
   ```

2. **Verify Files:**
   ```bash
   ls python-api/models/  # Harus ada .joblib dan .json
   ls python-api/.env     # Harus ada
   ```

3. **Test Step-by-Step:**
   ```python
   # test_import.py
   import torch
   import sklearn
   import flask
   from supabase import create_client
   print("All imports OK!")
   ```

4. **Check Logs:**
   ```bash
   python app.py 2>&1 | tee error.log
   # Kirim error.log untuk analisis
   ```

5. **Minimal Test:**
   ```bash
   curl -X POST http://localhost:5000/classify \
     -H "Content-Type: application/json" \
     -d '{"image": "data:image/jpeg;base64,/9j/4AAQ..."}'
   ```

---

## πŸ“š References

- [Python API README](./README.md)
- [Supabase Setup Guide](./SUPABASE_SETUP.md)
- [Model Setup Guide](./CARA_MELETAKKAN_FILE_MODEL.md)
- [Main Project README](../README.md)
- [Environment Setup](../ENVIRONMENT_SETUP.md)

## πŸ’‘ Tips

1. **Always use virtual environment** untuk avoid dependency conflicts
2. **Check logs first** sebelum cari solusi lain
3. **Test locally** sebelum deploy to production
4. **Keep dependencies updated** tapi test dulu di local
5. **Use GPU** di production untuk performance

---

**Butuh bantuan lebih lanjut?** Check dokumentasi atau review error logs secara detail.