Codewithsalty commited on
Commit
ac416f7
·
verified ·
1 Parent(s): a4a23df

Update newapi.py

Browse files
Files changed (1) hide show
  1. newapi.py +10 -14
newapi.py CHANGED
@@ -11,16 +11,15 @@ from huggingface_hub import hf_hub_download
11
  from models.TumorModel import TumorClassification, GliomaStageModel
12
  from utils import get_precautions_from_gemini
13
 
14
- # ✅ Writable cache directory inside project
15
- cache_dir = "./hf_cache"
16
 
17
- # Create the directory if it doesn't exist
18
- os.makedirs(cache_dir, exist_ok=True)
19
 
20
  # Initialize FastAPI app
21
  app = FastAPI(title="Brain Tumor Detection API")
22
 
23
- # Enable CORS for all origins
24
  app.add_middleware(
25
  CORSMiddleware,
26
  allow_origins=["*"],
@@ -29,7 +28,7 @@ app.add_middleware(
29
  allow_headers=["*"],
30
  )
31
 
32
- # Load Tumor Classification Model
33
  btd_model_path = hf_hub_download(
34
  repo_id="Codewithsalty/brain-tumor-models",
35
  filename="BTD_model.pth",
@@ -39,7 +38,7 @@ tumor_model = TumorClassification()
39
  tumor_model.load_state_dict(torch.load(btd_model_path, map_location="cpu"))
40
  tumor_model.eval()
41
 
42
- # Load Glioma Stage Prediction Model
43
  glioma_model_path = hf_hub_download(
44
  repo_id="Codewithsalty/brain-tumor-models",
45
  filename="glioma_stages.pth",
@@ -49,7 +48,7 @@ glioma_model = GliomaStageModel()
49
  glioma_model.load_state_dict(torch.load(glioma_model_path, map_location="cpu"))
50
  glioma_model.eval()
51
 
52
- # Image preprocessing pipeline
53
  transform = transforms.Compose([
54
  transforms.Grayscale(),
55
  transforms.Resize((224, 224)),
@@ -57,15 +56,13 @@ transform = transforms.Compose([
57
  transforms.Normalize(mean=[0.5], std=[0.5]),
58
  ])
59
 
60
- # Health check
61
  @app.get("/")
62
  async def root():
63
  return {"message": "Brain Tumor Detection API is running."}
64
 
65
- # Tumor type labels
66
  labels = ['glioma', 'meningioma', 'notumor', 'pituitary']
67
 
68
- # Predict tumor type from image
69
  @app.post("/predict-image")
70
  async def predict_image(file: UploadFile = File(...)):
71
  img_bytes = await file.read()
@@ -83,7 +80,7 @@ async def predict_image(file: UploadFile = File(...)):
83
  precautions = get_precautions_from_gemini(tumor_type)
84
  return {"tumor_type": tumor_type, "precaution": precautions}
85
 
86
- # Mutation input model
87
  class MutationInput(BaseModel):
88
  gender: str
89
  age: float
@@ -95,7 +92,6 @@ class MutationInput(BaseModel):
95
  cic: int
96
  pik3ca: int
97
 
98
- # Predict glioma stage
99
  @app.post("/predict-glioma-stage")
100
  async def predict_glioma_stage(data: MutationInput):
101
  gender_val = 0 if data.gender.lower() == 'm' else 1
@@ -111,7 +107,7 @@ async def predict_glioma_stage(data: MutationInput):
111
  stages = ['Stage 1', 'Stage 2', 'Stage 3', 'Stage 4']
112
  return {"glioma_stage": stages[idx]}
113
 
114
- # Run locally (ignored on Spaces, used only for dev/testing)
115
  if __name__ == "__main__":
116
  import uvicorn
117
  uvicorn.run("newapi:app", host="0.0.0.0", port=10000)
 
11
  from models.TumorModel import TumorClassification, GliomaStageModel
12
  from utils import get_precautions_from_gemini
13
 
14
+ # ✅ Use Hugging Face's built-in writable cache directory
15
+ cache_dir = "/home/user/.cache/huggingface"
16
 
17
+ # No need to call os.makedirs directory already exists
 
18
 
19
  # Initialize FastAPI app
20
  app = FastAPI(title="Brain Tumor Detection API")
21
 
22
+ # Enable CORS
23
  app.add_middleware(
24
  CORSMiddleware,
25
  allow_origins=["*"],
 
28
  allow_headers=["*"],
29
  )
30
 
31
+ # Load tumor classification model
32
  btd_model_path = hf_hub_download(
33
  repo_id="Codewithsalty/brain-tumor-models",
34
  filename="BTD_model.pth",
 
38
  tumor_model.load_state_dict(torch.load(btd_model_path, map_location="cpu"))
39
  tumor_model.eval()
40
 
41
+ # Load glioma stage model
42
  glioma_model_path = hf_hub_download(
43
  repo_id="Codewithsalty/brain-tumor-models",
44
  filename="glioma_stages.pth",
 
48
  glioma_model.load_state_dict(torch.load(glioma_model_path, map_location="cpu"))
49
  glioma_model.eval()
50
 
51
+ # Image preprocessing
52
  transform = transforms.Compose([
53
  transforms.Grayscale(),
54
  transforms.Resize((224, 224)),
 
56
  transforms.Normalize(mean=[0.5], std=[0.5]),
57
  ])
58
 
 
59
  @app.get("/")
60
  async def root():
61
  return {"message": "Brain Tumor Detection API is running."}
62
 
63
+ # Labels
64
  labels = ['glioma', 'meningioma', 'notumor', 'pituitary']
65
 
 
66
  @app.post("/predict-image")
67
  async def predict_image(file: UploadFile = File(...)):
68
  img_bytes = await file.read()
 
80
  precautions = get_precautions_from_gemini(tumor_type)
81
  return {"tumor_type": tumor_type, "precaution": precautions}
82
 
83
+ # Mutation input
84
  class MutationInput(BaseModel):
85
  gender: str
86
  age: float
 
92
  cic: int
93
  pik3ca: int
94
 
 
95
  @app.post("/predict-glioma-stage")
96
  async def predict_glioma_stage(data: MutationInput):
97
  gender_val = 0 if data.gender.lower() == 'm' else 1
 
107
  stages = ['Stage 1', 'Stage 2', 'Stage 3', 'Stage 4']
108
  return {"glioma_stage": stages[idx]}
109
 
110
+ # For local development only
111
  if __name__ == "__main__":
112
  import uvicorn
113
  uvicorn.run("newapi:app", host="0.0.0.0", port=10000)