|
| 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 | + |
1 | 61 | # Build a breakdown dictionary |
2 | 62 | breakdown = { |
3 | 63 | "Candidate Planet": round(float(proba[0]) * 100, 2), |
4 | 64 | "Confirmed Planet": round(float(proba[1]) * 100, 2), |
5 | 65 | "False Positive": round(float(proba[2]) * 100, 2) |
6 | 66 | } |
7 | | - |
8 | | - # Construct the response message |
9 | 67 | message = f"Your ExoPlanet is a {labels[pred_num]} ({confidence}% confident)." |
10 | 68 |
|
11 | 69 | return { |
12 | 70 | "prediction_label": labels[pred_num], |
13 | 71 | "prediction_numeric": pred_num, |
14 | 72 | "confidence_percent": confidence, |
15 | | - "breakdown_percent": breakdown, |
16 | | - "message": message |
| 73 | + "breakdown_percent": breakdown |
17 | 74 | } |
| 75 | + |
| 76 | + |
0 commit comments