Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import joblib
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
|
| 7 |
+
# 1. Uygulamayı Başlat
|
| 8 |
+
app = FastAPI(title="Credit Risk API", description="Kredi Risk Tahmin Modeli Servisi")
|
| 9 |
+
|
| 10 |
+
# 2. CORS Ayarları (Frontend'in bu API'ye erişebilmesi için gerekli)
|
| 11 |
+
app.add_middleware(
|
| 12 |
+
CORSMiddleware,
|
| 13 |
+
allow_origins=["*"], # Güvenlik için gerçek projede sadece frontend URL'ini yazın
|
| 14 |
+
allow_credentials=True,
|
| 15 |
+
allow_methods=["*"],
|
| 16 |
+
allow_headers=["*"],
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
# 3. Eğitilmiş Modeli Yükle
|
| 20 |
+
try:
|
| 21 |
+
model = joblib.load('credit_risk_model.pkl')
|
| 22 |
+
print("Model başarıyla yüklendi.")
|
| 23 |
+
except Exception as e:
|
| 24 |
+
print(f"Model yüklenirken hata oluştu: {e}")
|
| 25 |
+
# Hata durumunda boş bir model değişkeni (Uygulama çökmesin diye)
|
| 26 |
+
model = None
|
| 27 |
+
|
| 28 |
+
# 4. Veri Modeli (Frontend'den beklenen veri formatı)
|
| 29 |
+
# Buradaki isimler CSV'deki kolon isimleriyle birebir aynı olmalı.
|
| 30 |
+
class LoanApplication(BaseModel):
|
| 31 |
+
person_age: int
|
| 32 |
+
person_income: float
|
| 33 |
+
person_home_ownership: str # Örn: RENT, OWN, MORTGAGE
|
| 34 |
+
person_emp_length: float
|
| 35 |
+
loan_intent: str # Örn: EDUCATION, MEDICAL, VENTURE
|
| 36 |
+
loan_grade: str # Örn: A, B, C, D
|
| 37 |
+
loan_amnt: float
|
| 38 |
+
loan_int_rate: float
|
| 39 |
+
loan_percent_income: float
|
| 40 |
+
cb_person_default_on_file: str # Y veya N
|
| 41 |
+
cb_person_cred_hist_length: int
|
| 42 |
+
|
| 43 |
+
# 5. Ana Sayfa (Health Check)
|
| 44 |
+
@app.get("/")
|
| 45 |
+
def read_root():
|
| 46 |
+
return {"message": "Credit Risk API Çalışıyor! /docs adresine giderek test edebilirsin."}
|
| 47 |
+
|
| 48 |
+
# 6. Tahmin Endpoint'i
|
| 49 |
+
@app.post("/predict")
|
| 50 |
+
def predict_risk(data: LoanApplication):
|
| 51 |
+
if not model:
|
| 52 |
+
raise HTTPException(status_code=500, detail="Model yüklenemedi, sunucu hatası.")
|
| 53 |
+
|
| 54 |
+
# Gelen veriyi (JSON) Pandas DataFrame'e çevir
|
| 55 |
+
# Çünkü modelimiz (Pipeline) DataFrame bekliyor.
|
| 56 |
+
input_df = pd.DataFrame([data.dict()])
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
# Tahmin Yap
|
| 60 |
+
prediction = model.predict(input_df)[0] # 0 veya 1 döner
|
| 61 |
+
probability = model.predict_proba(input_df)[0][1] # 1 olma (Batık) ihtimali
|
| 62 |
+
|
| 63 |
+
# Sonucu Hazırla
|
| 64 |
+
result = {
|
| 65 |
+
"prediction": int(prediction),
|
| 66 |
+
"risk_score": round(float(probability), 4),
|
| 67 |
+
"risk_status": "Yüksek Risk (Red)" if prediction == 1 else "Düşük Risk (Onay)",
|
| 68 |
+
"risk_percentage": f"%{round(probability * 100, 2)}"
|
| 69 |
+
}
|
| 70 |
+
return result
|
| 71 |
+
|
| 72 |
+
except Exception as e:
|
| 73 |
+
raise HTTPException(status_code=500, detail=f"Tahmin sırasında hata: {str(e)}")
|
| 74 |
+
|
| 75 |
+
# Bu dosya 'python main.py' ile çalıştırılırsa uvicorn'u tetikle
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
import uvicorn
|
| 78 |
+
uvicorn.run(app, host="127.0.0.1", port=8000)
|