π§ 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
pip uninstall scikit-learn -y
pip install scikit-learn==1.3.2
Option 2: Install semua dependencies ulang
cd python-api
pip install -r requirements.txt
Option 3: Gunakan virtual environment (Recommended)
# 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
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
cd python-api
copy .env.example .env # Windows
# atau
cp .env.example .env # Linux/Mac
2. Edit .env dengan credentials yang benar:
SUPABASE_URL=https://xyddxrfiacdcnipdclas.supabase.co
SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
3. Restart server:
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:
# Windows
dir python-api\models
# Linux/Mac
ls -lh python-api/models/
π Panduan lengkap: Lihat CARA_MELETAKKAN_FILE_MODEL.md
π Error: CORS Issues
Problem
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:
pip show flask-cors
2. Check app.py line 15:
CORS(app) # Pastikan ini ada
3. Restart server
Verifikasi
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
- Environment variables tidak diset
- RLS policies terlalu restrictive
- Table schema tidak sesuai
Solusi
1. Check environment variables:
import os
print(os.getenv('SUPABASE_URL'))
print(os.getenv('SUPABASE_ANON_KEY'))
2. Check Supabase RLS policies:
-- Di Supabase SQL Editor
SELECT * FROM pg_policies WHERE tablename = 'predictions';
3. Verify table structure:
\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:
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:
# 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
- Model reload setiap request
- CPU-only inference
- Large image size
Solusi
1. Model caching (Already implemented):
# app.py - Model loaded once saat startup
model = load_model() # Global variable
2. Image optimization:
# 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:
python --version
# Harus: Python 3.10.x atau 3.11.x
2. Install torch dengan index URL:
# 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:
python -m pip install --upgrade pip
π Error: "Connection refused"
Problem
ConnectionError: HTTPConnectionPool(host='localhost', port=5000):
Max retries exceeded with url: /classify
Penyebab
- Server tidak running
- Port sudah dipakai
- Firewall blocking
Solusi
1. Check server status:
# Harus tampil: "Running on http://127.0.0.1:5000"
python app.py
2. Check port:
# Windows
netstat -ano | findstr :5000
# Linux/Mac
lsof -i :5000
3. Gunakan port lain:
# Di .env
PORT=5001
4. Test dengan curl:
curl http://localhost:5000/health
# Expected: {"status": "ok"}
π Logging & Debugging
Enable Debug Mode
# 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
# Lihat full error trace
python app.py 2>&1 | tee api.log
Test Endpoints
# 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:
# 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:
# Pastikan requirements.txt complete
pip freeze > requirements.txt
Environment Variables
Problem: Env vars tidak terbaca di production
Solution:
- Set via platform dashboard (Railway/Hugging Face)
- Jangan commit
.envke git - Verify dengan
/healthendpoint
π Masih Bermasalah?
Langkah Debugging Sistematis
Check Prerequisites:
python --version # 3.10+ pip list | grep -E "torch|sklearn|flask"Verify Files:
ls python-api/models/ # Harus ada .joblib dan .json ls python-api/.env # Harus adaTest Step-by-Step:
# test_import.py import torch import sklearn import flask from supabase import create_client print("All imports OK!")Check Logs:
python app.py 2>&1 | tee error.log # Kirim error.log untuk analisisMinimal Test:
curl -X POST http://localhost:5000/classify \ -H "Content-Type: application/json" \ -d '{"image": "data:image/jpeg;base64,/9j/4AAQ..."}'
π References
π‘ Tips
- Always use virtual environment untuk avoid dependency conflicts
- Check logs first sebelum cari solusi lain
- Test locally sebelum deploy to production
- Keep dependencies updated tapi test dulu di local
- Use GPU di production untuk performance
Butuh bantuan lebih lanjut? Check dokumentasi atau review error logs secara detail.