Skip to content

Commit 6ce2e10

Browse files
authored
Update api.py
1 parent be55af8 commit 6ce2e10

1 file changed

Lines changed: 63 additions & 4 deletions

File tree

backend/api.py

Lines changed: 63 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,76 @@
1+
from fastapi import FastAPI
2+
from fastapi.middleware.cors import CORSMiddleware
3+
from joblib import load
4+
import numpy as np
5+
6+
app = FastAPI()
7+
8+
# Allow website access (CORS)
9+
app.add_middleware(
10+
CORSMiddleware,
11+
allow_origins=["*"], # Allow all for now
12+
allow_credentials=True
13+
allow_methods=["*"],
14+
allow_headers=["*"],
15+
)
16+
17+
import os
18+
import requests
19+
from joblib import load
20+
21+
MODEL_URL = "https://drive.google.com/uc?export=download&id=12rjb9yNzg1Jw8mFY22VXS4nEcbx_1Znw"
22+
MODEL_PATH = "ExoPlanet_Classifier.joblib"
23+
24+
# Download model if not present locally
25+
if not os.path.exists(MODEL_PATH):
26+
print("Downloading model from Google Drive...")
27+
response = requests.get(MODEL_URL)
28+
response.raise_for_status()
29+
with open(MODEL_PATH, "wb") as f:
30+
f.write(response.content)
31+
print("Model downloaded!")
32+
33+
# Load the model
34+
model = load(MODEL_PATH)
35+
print("Model loaded successfully!")
36+
37+
38+
@app.get("/")
39+
def home():
40+
return {"message": "Backend is running"}
41+
42+
@app.post("/predict")
43+
async def predict(data: dict):
44+
# Extract inputs
45+
inputs = np.array(data["inputs"]).reshape(1, -1)
46+
47+
# Make prediction
48+
pred_num = int(model.predict(inputs)[0])
49+
proba = model.predict_proba(inputs)[0] # probability breakdown
50+
51+
# Label mapping
52+
labels = {
53+
0: "Candidate Planet",
54+
1: "Confirmed Planet",
55+
2: "False Positive"
56+
}
57+
58+
# Confidence for the predicted class
59+
confidence = round(float(proba[pred_num]) * 100, 2)
60+
161
# Build a breakdown dictionary
262
breakdown = {
363
"Candidate Planet": round(float(proba[0]) * 100, 2),
464
"Confirmed Planet": round(float(proba[1]) * 100, 2),
565
"False Positive": round(float(proba[2]) * 100, 2)
666
}
7-
8-
# Construct the response message
967
message = f"Your ExoPlanet is a {labels[pred_num]} ({confidence}% confident)."
1068

1169
return {
1270
"prediction_label": labels[pred_num],
1371
"prediction_numeric": pred_num,
1472
"confidence_percent": confidence,
15-
"breakdown_percent": breakdown,
16-
"message": message
73+
"breakdown_percent": breakdown
1774
}
75+
76+

0 commit comments

Comments
 (0)