seedling-classifier / python-api /TROUBLESHOOTING.md
hanya70999's picture
Upload 13 files
72b9a21 verified

πŸ”§ 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

  1. Environment variables tidak diset
  2. RLS policies terlalu restrictive
  3. 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

  1. Model reload setiap request
  2. CPU-only inference
  3. 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

  1. Server tidak running
  2. Port sudah dipakai
  3. 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:

  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:

    python --version  # 3.10+
    pip list | grep -E "torch|sklearn|flask"
    
  2. Verify Files:

    ls python-api/models/  # Harus ada .joblib dan .json
    ls python-api/.env     # Harus ada
    
  3. Test Step-by-Step:

    # test_import.py
    import torch
    import sklearn
    import flask
    from supabase import create_client
    print("All imports OK!")
    
  4. Check Logs:

    python app.py 2>&1 | tee error.log
    # Kirim error.log untuk analisis
    
  5. Minimal Test:

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

πŸ“š References

πŸ’‘ 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.