# 🔧 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.