Spaces:
Sleeping
Sleeping
Upload 6 files
Browse files- DEPLOYMENT_STEPS.txt +169 -0
- Dockerfile +21 -0
- README.md +95 -11
- app.py +129 -0
- requirements.txt +7 -0
- test_deployed_api.py +82 -0
DEPLOYMENT_STEPS.txt
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
================================================================================
|
| 2 |
+
HUGGING FACE SPACES DEPLOYMENT - ADIM ADIM
|
| 3 |
+
================================================================================
|
| 4 |
+
|
| 5 |
+
📁 HAZIR DOSYALAR:
|
| 6 |
+
✓ Dockerfile
|
| 7 |
+
✓ app.py
|
| 8 |
+
✓ requirements.txt
|
| 9 |
+
✓ README.md
|
| 10 |
+
✓ test_deployed_api.py
|
| 11 |
+
|
| 12 |
+
================================================================================
|
| 13 |
+
ADIMLAR:
|
| 14 |
+
================================================================================
|
| 15 |
+
|
| 16 |
+
1️⃣ HUGGING FACE'E GİT
|
| 17 |
+
URL: https://huggingface.co/new-space
|
| 18 |
+
|
| 19 |
+
Hesabın yoksa önce kayıt ol:
|
| 20 |
+
https://huggingface.co/join
|
| 21 |
+
|
| 22 |
+
--------------------------------------------------------------------------------
|
| 23 |
+
|
| 24 |
+
2️⃣ YENİ SPACE OLUŞTUR
|
| 25 |
+
|
| 26 |
+
⚙️ AYARLAR:
|
| 27 |
+
|
| 28 |
+
Space name: dog-breed-api
|
| 29 |
+
(veya istediğin isim)
|
| 30 |
+
|
| 31 |
+
Space SDK: 🐳 Docker ⚠️ ÇOK ÖNEMLİ!
|
| 32 |
+
(Gradio veya Streamlit DEĞİL - sadece Docker!)
|
| 33 |
+
|
| 34 |
+
Space hardware: CPU basic - Free
|
| 35 |
+
|
| 36 |
+
Visibility: Public
|
| 37 |
+
|
| 38 |
+
➤ "Create Space" tıkla
|
| 39 |
+
|
| 40 |
+
--------------------------------------------------------------------------------
|
| 41 |
+
|
| 42 |
+
3️⃣ DOSYALARI YÜKLE
|
| 43 |
+
|
| 44 |
+
Space açıldıktan sonra:
|
| 45 |
+
|
| 46 |
+
a) Üstteki "+ Add file" → "Upload files" tıkla
|
| 47 |
+
|
| 48 |
+
b) Şu SIRAYA GÖRE dosyaları yükle:
|
| 49 |
+
|
| 50 |
+
1. Dockerfile
|
| 51 |
+
2. requirements.txt
|
| 52 |
+
3. app.py
|
| 53 |
+
4. README.md (opsiyonel)
|
| 54 |
+
|
| 55 |
+
c) Her dosyadan sonra "Commit changes to main" tıkla
|
| 56 |
+
|
| 57 |
+
--------------------------------------------------------------------------------
|
| 58 |
+
|
| 59 |
+
4️⃣ BUILD İZLE
|
| 60 |
+
|
| 61 |
+
Dosyalar yüklendikten sonra:
|
| 62 |
+
|
| 63 |
+
- "App" sekmesine geç
|
| 64 |
+
- "Building..." yazısını göreceksin
|
| 65 |
+
- Logs açılacak
|
| 66 |
+
|
| 67 |
+
⏱️ Bekleme: 5-10 dakika
|
| 68 |
+
|
| 69 |
+
Loglar:
|
| 70 |
+
┌─────────────────────────────────────┐
|
| 71 |
+
│ Building Docker image... │
|
| 72 |
+
│ Installing dependencies... │
|
| 73 |
+
│ Downloading model (200+ MB)... │
|
| 74 |
+
│ Starting application... │
|
| 75 |
+
│ ✓ Running on port 7860 │
|
| 76 |
+
└─────────────────────────────────────┘
|
| 77 |
+
|
| 78 |
+
Başarılı olunca: ✓ Running
|
| 79 |
+
|
| 80 |
+
--------------------------------------------------------------------------------
|
| 81 |
+
|
| 82 |
+
5️⃣ TEST ET!
|
| 83 |
+
|
| 84 |
+
Space URL'in:
|
| 85 |
+
https://KULLANICI-ADIN-dog-breed-api.hf.space
|
| 86 |
+
|
| 87 |
+
API Endpoint:
|
| 88 |
+
https://KULLANICI-ADIN-dog-breed-api.hf.space/predict_pet
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
📝 Test scripti ile:
|
| 92 |
+
|
| 93 |
+
a) test_deployed_api.py dosyasını aç
|
| 94 |
+
|
| 95 |
+
b) İlk satırı düzenle:
|
| 96 |
+
SPACE_URL = "https://SENIN-KULLANICI-ADIN-dog-breed-api.hf.space"
|
| 97 |
+
|
| 98 |
+
c) Çalıştır:
|
| 99 |
+
python test_deployed_api.py
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
🌐 Browser'da test:
|
| 103 |
+
|
| 104 |
+
a) https://KULLANICI-ADIN-dog-breed-api.hf.space/ aç
|
| 105 |
+
→ Sağlık kontrolü göreceksin (JSON)
|
| 106 |
+
|
| 107 |
+
b) Postman/Insomnia kullan:
|
| 108 |
+
- URL: .../predict_pet
|
| 109 |
+
- Method: POST
|
| 110 |
+
- Body: form-data
|
| 111 |
+
- Key: image (file type)
|
| 112 |
+
- Value: Bir köpek fotoğrafı seç
|
| 113 |
+
|
| 114 |
+
================================================================================
|
| 115 |
+
BAŞARILI OLDUKTAN SONRA:
|
| 116 |
+
================================================================================
|
| 117 |
+
|
| 118 |
+
✅ API'n hazır!
|
| 119 |
+
|
| 120 |
+
📡 Endpoint:
|
| 121 |
+
https://KULLANICI-ADIN-dog-breed-api.hf.space/predict_pet
|
| 122 |
+
|
| 123 |
+
📊 Kullanım örnekleri:
|
| 124 |
+
- README.md dosyasına bak
|
| 125 |
+
- Python, JavaScript, cURL örnekleri var
|
| 126 |
+
|
| 127 |
+
⚡ Performans:
|
| 128 |
+
- İlk istek: 10-15s (model yükleme)
|
| 129 |
+
- Sonraki: 2-4s (hızlı!)
|
| 130 |
+
|
| 131 |
+
💰 Maliyet:
|
| 132 |
+
- TAMAMEN ÜCRETSİZ! (Public Space)
|
| 133 |
+
|
| 134 |
+
================================================================================
|
| 135 |
+
SORUN GİDERME
|
| 136 |
+
================================================================================
|
| 137 |
+
|
| 138 |
+
❌ "Building failed"
|
| 139 |
+
→ Logs'a bak, hata mesajını gör
|
| 140 |
+
→ Dockerfile'ı kontrol et
|
| 141 |
+
→ requirements.txt'yi kontrol et
|
| 142 |
+
|
| 143 |
+
❌ "503 Service Unavailable"
|
| 144 |
+
→ Space henüz başlamadı, 1-2 dakika bekle
|
| 145 |
+
|
| 146 |
+
❌ "Out of memory"
|
| 147 |
+
→ Model çok büyük, ücretli tier gerek
|
| 148 |
+
→ Ya da daha küçük model kullan
|
| 149 |
+
|
| 150 |
+
❌ Fotoğraf yüklenmiyor
|
| 151 |
+
→ Dosya boyutu max 10MB olmalı
|
| 152 |
+
→ Format: JPEG, PNG, WebP
|
| 153 |
+
|
| 154 |
+
================================================================================
|
| 155 |
+
İPUCU: Space'i aktif tut
|
| 156 |
+
================================================================================
|
| 157 |
+
|
| 158 |
+
Hugging Face Spaces'te free tier'da Space'ler inaktifse uyku moduna girer.
|
| 159 |
+
|
| 160 |
+
İlk istekte tekrar uyanır (10-15 saniye sürer).
|
| 161 |
+
|
| 162 |
+
Sürekli aktif tutmak için:
|
| 163 |
+
- Her gün 1 istek at
|
| 164 |
+
- Ya da ücretli tier'a geç (always-on)
|
| 165 |
+
|
| 166 |
+
================================================================================
|
| 167 |
+
BAŞARILAR! 🚀
|
| 168 |
+
================================================================================
|
| 169 |
+
|
Dockerfile
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Install dependencies
|
| 6 |
+
COPY requirements_deployment.txt requirements.txt
|
| 7 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 8 |
+
|
| 9 |
+
# Copy app
|
| 10 |
+
COPY app_deployment.py app.py
|
| 11 |
+
|
| 12 |
+
# Expose port
|
| 13 |
+
EXPOSE 7860
|
| 14 |
+
|
| 15 |
+
# Set environment
|
| 16 |
+
ENV PORT=7860
|
| 17 |
+
ENV PYTHONUNBUFFERED=1
|
| 18 |
+
|
| 19 |
+
# Run app
|
| 20 |
+
CMD ["python", "app.py"]
|
| 21 |
+
|
README.md
CHANGED
|
@@ -1,11 +1,95 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🐕 Dog Breed Classification API
|
| 2 |
+
|
| 3 |
+
ConvNextV2-large-DogBreed model ile köpek ırkı tahmini yapan API.
|
| 4 |
+
|
| 5 |
+
## 🚀 Kullanım
|
| 6 |
+
|
| 7 |
+
### Endpoint
|
| 8 |
+
|
| 9 |
+
```
|
| 10 |
+
POST /predict_pet
|
| 11 |
+
```
|
| 12 |
+
|
| 13 |
+
### Request
|
| 14 |
+
|
| 15 |
+
**Content-Type:** `multipart/form-data`
|
| 16 |
+
|
| 17 |
+
**Body:**
|
| 18 |
+
- `image` (file): Köpek fotoğrafı (JPEG, PNG, WebP)
|
| 19 |
+
|
| 20 |
+
### Response
|
| 21 |
+
|
| 22 |
+
```json
|
| 23 |
+
{
|
| 24 |
+
"breed": "Doberman_pinscher",
|
| 25 |
+
"confidence": 0.533,
|
| 26 |
+
"top_5": [
|
| 27 |
+
{"breed": "Doberman_pinscher", "confidence": 0.533},
|
| 28 |
+
{"breed": "Beauceron", "confidence": 0.065},
|
| 29 |
+
{"breed": "German_pinscher", "confidence": 0.041},
|
| 30 |
+
{"breed": "Black_and_tan_coonhound", "confidence": 0.023},
|
| 31 |
+
{"breed": "Greater_swiss_mountain_dog", "confidence": 0.011}
|
| 32 |
+
],
|
| 33 |
+
"model": "ConvNextV2-large-DogBreed",
|
| 34 |
+
"accuracy": "91.39%"
|
| 35 |
+
}
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
## 📝 Örnekler
|
| 39 |
+
|
| 40 |
+
### Python
|
| 41 |
+
|
| 42 |
+
```python
|
| 43 |
+
import requests
|
| 44 |
+
|
| 45 |
+
url = "https://YOUR-SPACE-URL.hf.space/predict_pet"
|
| 46 |
+
|
| 47 |
+
with open("dog.jpg", "rb") as f:
|
| 48 |
+
files = {"image": f}
|
| 49 |
+
response = requests.post(url, files=files)
|
| 50 |
+
|
| 51 |
+
result = response.json()
|
| 52 |
+
print(f"Breed: {result['breed']}")
|
| 53 |
+
print(f"Confidence: {result['confidence']:.2%}")
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
### cURL
|
| 57 |
+
|
| 58 |
+
```bash
|
| 59 |
+
curl -X POST https://YOUR-SPACE-URL.hf.space/predict_pet \
|
| 60 |
+
-F "image=@dog.jpg"
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
### JavaScript (Fetch)
|
| 64 |
+
|
| 65 |
+
```javascript
|
| 66 |
+
const formData = new FormData();
|
| 67 |
+
formData.append('image', fileInput.files[0]);
|
| 68 |
+
|
| 69 |
+
const response = await fetch('https://YOUR-SPACE-URL.hf.space/predict_pet', {
|
| 70 |
+
method: 'POST',
|
| 71 |
+
body: formData
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
const result = await response.json();
|
| 75 |
+
console.log(result.breed, result.confidence);
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
## ℹ️ Model Bilgisi
|
| 79 |
+
|
| 80 |
+
- **Model:** [Pavarissy/ConvNextV2-large-DogBreed](https://huggingface.co/Pavarissy/ConvNextV2-large-DogBreed)
|
| 81 |
+
- **Accuracy:** 91.39% (validation set)
|
| 82 |
+
- **Architecture:** ConvNextV2-large-22k-224
|
| 83 |
+
- **Training:** 50 epochs, Stanford Dogs Dataset
|
| 84 |
+
- **Classes:** 120 dog breeds
|
| 85 |
+
|
| 86 |
+
## 🔧 Performans
|
| 87 |
+
|
| 88 |
+
- **İlk istek:** 10-15 saniye (model yükleme)
|
| 89 |
+
- **Sonraki istekler:** 2-4 saniye
|
| 90 |
+
- **Hardware:** CPU basic (HF Spaces free tier)
|
| 91 |
+
|
| 92 |
+
## 📄 License
|
| 93 |
+
|
| 94 |
+
MIT
|
| 95 |
+
|
app.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Production-ready Flask backend for deployment
|
| 3 |
+
Optimized for Hugging Face Spaces / Railway / Render
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from flask import Flask, request, jsonify
|
| 7 |
+
import io
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from flask_cors import CORS
|
| 10 |
+
import logging
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
app = Flask(__name__)
|
| 14 |
+
CORS(app, resources={r"/predict_pet": {"origins": "*"}})
|
| 15 |
+
|
| 16 |
+
# Logging configuration
|
| 17 |
+
logging.basicConfig(
|
| 18 |
+
level=logging.INFO,
|
| 19 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 20 |
+
)
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
# Model global variables
|
| 24 |
+
model = None
|
| 25 |
+
image_processor = None
|
| 26 |
+
|
| 27 |
+
def load_model():
|
| 28 |
+
"""Load model on first request"""
|
| 29 |
+
global model, image_processor
|
| 30 |
+
|
| 31 |
+
if model is not None:
|
| 32 |
+
return
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
import torch
|
| 36 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
| 37 |
+
|
| 38 |
+
logger.info("Loading ConvNextV2-large-DogBreed model...")
|
| 39 |
+
|
| 40 |
+
model_name = "Pavarissy/ConvNextV2-large-DogBreed"
|
| 41 |
+
|
| 42 |
+
# Detect device
|
| 43 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 44 |
+
logger.info(f"Using device: {device}")
|
| 45 |
+
|
| 46 |
+
# Load model
|
| 47 |
+
image_processor = AutoImageProcessor.from_pretrained(model_name)
|
| 48 |
+
model = AutoModelForImageClassification.from_pretrained(model_name)
|
| 49 |
+
model = model.to(device)
|
| 50 |
+
model.eval()
|
| 51 |
+
|
| 52 |
+
logger.info(f"✓ Model loaded successfully on {device}")
|
| 53 |
+
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logger.error(f"Failed to load model: {e}")
|
| 56 |
+
raise
|
| 57 |
+
|
| 58 |
+
@app.route('/', methods=['GET'])
|
| 59 |
+
def health_check():
|
| 60 |
+
"""Health check endpoint"""
|
| 61 |
+
return jsonify({
|
| 62 |
+
'status': 'healthy',
|
| 63 |
+
'service': 'Dog Breed Prediction API',
|
| 64 |
+
'model': 'ConvNextV2-large-DogBreed',
|
| 65 |
+
'accuracy': '91.39%',
|
| 66 |
+
'version': '1.0.0'
|
| 67 |
+
})
|
| 68 |
+
|
| 69 |
+
@app.route('/predict_pet', methods=['POST'])
|
| 70 |
+
def predict_pet():
|
| 71 |
+
"""Predict dog breed from uploaded image"""
|
| 72 |
+
|
| 73 |
+
try:
|
| 74 |
+
# Load model if not loaded
|
| 75 |
+
load_model()
|
| 76 |
+
|
| 77 |
+
# Validate request
|
| 78 |
+
if 'image' not in request.files:
|
| 79 |
+
return jsonify({'error': 'No image file provided'}), 400
|
| 80 |
+
|
| 81 |
+
file = request.files['image']
|
| 82 |
+
|
| 83 |
+
# Read and validate image
|
| 84 |
+
image_bytes = file.read()
|
| 85 |
+
pil_image = Image.open(io.BytesIO(image_bytes))
|
| 86 |
+
|
| 87 |
+
if pil_image.mode != 'RGB':
|
| 88 |
+
pil_image = pil_image.convert('RGB')
|
| 89 |
+
|
| 90 |
+
# Make prediction
|
| 91 |
+
import torch
|
| 92 |
+
inputs = image_processor(pil_image, return_tensors="pt")
|
| 93 |
+
|
| 94 |
+
device = next(model.parameters()).device
|
| 95 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 96 |
+
|
| 97 |
+
with torch.no_grad():
|
| 98 |
+
outputs = model(**inputs)
|
| 99 |
+
logits = outputs.logits
|
| 100 |
+
|
| 101 |
+
probs = torch.nn.functional.softmax(logits, dim=-1)[0].cpu()
|
| 102 |
+
top_5_probs, top_5_indices = torch.topk(probs, 5)
|
| 103 |
+
|
| 104 |
+
# Format results
|
| 105 |
+
top_5_breeds = []
|
| 106 |
+
for prob, idx in zip(top_5_probs, top_5_indices):
|
| 107 |
+
top_5_breeds.append({
|
| 108 |
+
'breed': model.config.id2label[idx.item()],
|
| 109 |
+
'confidence': float(prob.item())
|
| 110 |
+
})
|
| 111 |
+
|
| 112 |
+
logger.info(f"Prediction: {top_5_breeds[0]['breed']} ({top_5_breeds[0]['confidence']:.2%})")
|
| 113 |
+
|
| 114 |
+
return jsonify({
|
| 115 |
+
'breed': top_5_breeds[0]['breed'],
|
| 116 |
+
'confidence': top_5_breeds[0]['confidence'],
|
| 117 |
+
'top_5': top_5_breeds,
|
| 118 |
+
'model': 'ConvNextV2-large-DogBreed',
|
| 119 |
+
'accuracy': '91.39%'
|
| 120 |
+
})
|
| 121 |
+
|
| 122 |
+
except Exception as e:
|
| 123 |
+
logger.error(f"Error: {str(e)}", exc_info=True)
|
| 124 |
+
return jsonify({'error': str(e)}), 500
|
| 125 |
+
|
| 126 |
+
if __name__ == '__main__':
|
| 127 |
+
port = int(os.environ.get('PORT', 7860))
|
| 128 |
+
app.run(host='0.0.0.0', port=port, debug=False)
|
| 129 |
+
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask==3.0.0
|
| 2 |
+
flask-cors==4.0.0
|
| 3 |
+
transformers==4.35.0
|
| 4 |
+
torch==2.1.0
|
| 5 |
+
pillow==10.1.0
|
| 6 |
+
accelerate==0.24.0
|
| 7 |
+
|
test_deployed_api.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Deployed HF Space API Test Scripti
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
# ⚠️ BURAYA KENDI SPACE URL'INI YAZ!
|
| 8 |
+
# Ornek: https://alpip-dog-breed-api.hf.space
|
| 9 |
+
SPACE_URL = "https://KULLANICI-ADIN-dog-breed-api.hf.space"
|
| 10 |
+
|
| 11 |
+
API_ENDPOINT = f"{SPACE_URL}/predict_pet"
|
| 12 |
+
|
| 13 |
+
# Test fotografi
|
| 14 |
+
image_path = r"C:\Users\alpip\OneDrive - Istanbul Bilgi Universitesi\Masaüstü\WhatsApp Image 2025-10-24 at 17.57.47.jpeg"
|
| 15 |
+
|
| 16 |
+
print("=" * 80)
|
| 17 |
+
print("DEPLOYED API TEST")
|
| 18 |
+
print("=" * 80)
|
| 19 |
+
print()
|
| 20 |
+
print(f"API Endpoint: {API_ENDPOINT}")
|
| 21 |
+
print(f"Test Image: {image_path}")
|
| 22 |
+
print()
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
# Health check once
|
| 26 |
+
print("1. Health check yapiliyor...")
|
| 27 |
+
response = requests.get(SPACE_URL)
|
| 28 |
+
if response.status_code == 200:
|
| 29 |
+
print(" ✓ Backend calisiyor!")
|
| 30 |
+
else:
|
| 31 |
+
print(f" ✗ Backend cevap vermiyor: {response.status_code}")
|
| 32 |
+
exit(1)
|
| 33 |
+
|
| 34 |
+
print()
|
| 35 |
+
print("2. Fotograf gonderiliyor...")
|
| 36 |
+
|
| 37 |
+
# Fotografi gonder
|
| 38 |
+
with open(image_path, 'rb') as f:
|
| 39 |
+
files = {'image': ('dog.jpg', f, 'image/jpeg')}
|
| 40 |
+
response = requests.post(API_ENDPOINT, files=files)
|
| 41 |
+
|
| 42 |
+
print(f" HTTP Status: {response.status_code}")
|
| 43 |
+
print()
|
| 44 |
+
|
| 45 |
+
if response.status_code == 200:
|
| 46 |
+
result = response.json()
|
| 47 |
+
|
| 48 |
+
print("=" * 80)
|
| 49 |
+
print("BASARILI! TAHMINLER:")
|
| 50 |
+
print("=" * 80)
|
| 51 |
+
|
| 52 |
+
for i, pred in enumerate(result['top_5'], 1):
|
| 53 |
+
breed = pred['breed']
|
| 54 |
+
confidence = pred['confidence'] * 100
|
| 55 |
+
bar = '#' * int(confidence / 2)
|
| 56 |
+
print(f"{i}. {breed:40s} {confidence:6.2f}% {bar}")
|
| 57 |
+
|
| 58 |
+
print("=" * 80)
|
| 59 |
+
print(f"EN IYI TAHMIN: {result['breed']} ({result['confidence']*100:.2f}%)")
|
| 60 |
+
print(f"Model: {result['model']}")
|
| 61 |
+
print(f"Accuracy: {result['accuracy']}")
|
| 62 |
+
print("=" * 80)
|
| 63 |
+
print()
|
| 64 |
+
print("API HAZIR! Kullanmaya baslayabilirsin!")
|
| 65 |
+
print()
|
| 66 |
+
print("Frontend'den kullanim:")
|
| 67 |
+
print(f" POST {API_ENDPOINT}")
|
| 68 |
+
print(" Body: form-data")
|
| 69 |
+
print(" Key: 'image' (file)")
|
| 70 |
+
|
| 71 |
+
else:
|
| 72 |
+
print(f"HATA: {response.status_code}")
|
| 73 |
+
print(response.text)
|
| 74 |
+
|
| 75 |
+
except FileNotFoundError:
|
| 76 |
+
print(f"Fotograf bulunamadi: {image_path}")
|
| 77 |
+
except requests.exceptions.ConnectionError:
|
| 78 |
+
print("Backend'e baglanilamadi!")
|
| 79 |
+
print("Space'in 'Running' durumunda oldugundan emin ol")
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print(f"Hata: {str(e)}")
|
| 82 |
+
|