Spaces:
Runtime error
Runtime error
Salman Khan commited on
Commit ·
e4acaca
1
Parent(s): eb6486f
Added brain tumor API project
Browse filesFiles changed (4)
- DockerfileAdded+26
- newapi.pyAdded+107
- requirements.txtAdded
- utils.pyAdded+25
1234567891011121314151617181920212223242526# Use an official Python runtime as a parent imageFROM python:3.10-slim
# Set environment variablesENV PYTHONDONTWRITEBYTECODE=1ENV PYTHONUNBUFFERED=1
# Set working directoryWORKDIR /app
# Install system dependenciesRUN apt-get update && apt-get install -y \ build-essential \ libgl1-mesa-glx \ && rm -rf /var/lib/apt/lists/*
# Copy requirements and installCOPY requirements.txt .RUN pip install --upgrade pipRUN pip install -r requirements.txt
# Copy the rest of the appCOPY . .
# Set the command to run your FastAPI app with uvicornCMD ["uvicorn", "newapi:app", "--host", "0.0.0.0", "--port", "8080"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107from fastapi import FastAPI, File, UploadFilefrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelimport torchfrom torchvision import transformsfrom PIL import Imageimport iofrom huggingface_hub import hf_hub_download
from models.TumorModel import TumorClassification, GliomaStageModelfrom utils import get_precautions_from_gemini
# Initialize FastAPI appapp = FastAPI(title="Brain Tumor Detection API")
# Enable CORS for all origins (adjust for production)app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# Load Tumor Classification Model from Hugging Facebtd_model_path = hf_hub_download( repo_id="Codewithsalty/brain-tumor-models", filename="BTD_model.pth")tumor_model = TumorClassification()tumor_model.load_state_dict(torch.load(btd_model_path, map_location="cpu"))tumor_model.eval()
# Load Glioma Stage Prediction Model from Hugging Faceglioma_model_path = hf_hub_download( repo_id="Codewithsalty/brain-tumor-models", filename="glioma_stages.pth")glioma_model = GliomaStageModel()glioma_model.load_state_dict(torch.load(glioma_model_path, map_location="cpu"))glioma_model.eval()
# Image preprocessing pipelinetransform = transforms.Compose([ transforms.Grayscale(), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.5], std=[0.5]),])
# Health check endpoint@app.get("/")async def root(): return {"message": "Brain Tumor Detection API is running."}
# Tumor type labelslabels = ['glioma', 'meningioma', 'notumor', 'pituitary']
# Predict tumor type from uploaded image@app.post("/predict-image")async def predict_image(file: UploadFile = File(...)): img_bytes = await file.read() img = Image.open(io.BytesIO(img_bytes)).convert("L") # Ensure grayscale x = transform(img).unsqueeze(0)
with torch.no_grad(): out = tumor_model(x) idx = torch.argmax(out, dim=1).item() tumor_type = labels[idx]
if tumor_type == "glioma": return {"tumor_type": tumor_type, "next": "submit_mutation_data"} else: precautions = get_precautions_from_gemini(tumor_type) return {"tumor_type": tumor_type, "precaution": precautions}
# Input model for glioma mutation dataclass MutationInput(BaseModel): gender: str age: float idh1: int tp53: int atrx: int pten: int egfr: int cic: int pik3ca: int
# Predict glioma stage based on mutations@app.post("/predict-glioma-stage")async def predict_glioma_stage(data: MutationInput): gender_val = 0 if data.gender.lower() == 'm' else 1 features = [ gender_val, data.age, data.idh1, data.tp53, data.atrx, data.pten, data.egfr, data.cic, data.pik3ca ] x = torch.tensor(features).float().unsqueeze(0)
with torch.no_grad(): out = glioma_model(x) idx = torch.argmax(out, dim=1).item() stages = ['Stage 1', 'Stage 2', 'Stage 3', 'Stage 4'] return {"glioma_stage": stages[idx]}
if __name__ == "__main__": import uvicorn uvicorn.run("newapi:app", host="0.0.0.0", port=10000)12345678910111213141516171819202122232425def get_user_test_data(): print("Enter the following details for prediction:")
gender_input = input("Gender (M/F): ").strip().lower() gender = 0 if gender_input == 'm' else 1 # Male = 0, Female = 1
age = float(input("Age at Diagnosis: "))
idh1 = int(input("IDH1 Mutation? (1 for Yes, 0 for No): ")) tp53 = int(input("TP53 Mutation? (1 for Yes, 0 for No): ")) atrx = int(input("ATRX Mutation? (1 for Yes, 0 for No): ")) pten = int(input("PTEN Mutation? (1 for Yes, 0 for No): ")) egfr = int(input("EGFR Mutation? (1 for Yes, 0 for No): ")) cic = int(input("CIC Mutation? (1 for Yes, 0 for No): ")) pik3ca = int(input("PIK3CA Mutation? (1 for Yes, 0 for No): "))
return [gender, age, idh1, tp53, atrx, pten, egfr, cic, pik3ca]
def get_precautions_from_gemini(tumor_type): precaution_db = { "meningioma": "Avoid radiation exposure and get regular check-ups.", "pituitary": "Monitor hormonal levels and follow medication strictly.", "notumor": "Stay healthy and get annual MRI scans if symptoms appear." } return precaution_db.get(tumor_type, "No specific precautions found.")DockerfileAdded+26
newapi.pyAdded+107
requirements.txtAdded
utils.pyAdded+25