Swapnilbpatil commited on
Commit
13da847
·
verified ·
1 Parent(s): 4f8eb1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -23
app.py CHANGED
@@ -1,7 +1,10 @@
1
- from fastapi import FastAPI, File, UploadFile, Request, HTTPException
2
- from fastapi.responses import HTMLResponse, JSONResponse
3
- from fastapi.templating import Jinja2Templates
4
  from fastapi.staticfiles import StaticFiles
 
 
 
5
  import tensorflow as tf
6
  from tensorflow.keras.models import load_model
7
  from tensorflow.keras.preprocessing.image import img_to_array, load_img
@@ -11,32 +14,22 @@ import base64
11
  from io import BytesIO
12
  from PIL import Image
13
  import shutil
 
14
 
15
- app = FastAPI(title="Kidney Disease Detection API")
 
16
 
17
  # Configure upload folder
18
  UPLOAD_FOLDER = 'uploads'
19
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
20
 
21
- # Templates setup
22
  templates = Jinja2Templates(directory="templates")
23
-
24
- # Mount static files
25
  app.mount("/static", StaticFiles(directory="static"), name="static")
26
 
27
- # Load model
28
  model = None
29
 
30
- def load_kidney_model():
31
- global model
32
- try:
33
- model = load_model("kidney_model/KIDNEY-Diseases.h5")
34
- print("Model loaded successfully!")
35
- return True
36
- except Exception as e:
37
- print(f"Error loading model: {e}")
38
- return False
39
-
40
  # Define class names based on dataset
41
  class_names = ['Cyst', 'Normal', 'Stone', 'Tumor']
42
 
@@ -48,7 +41,19 @@ class_descriptions = {
48
  'Tumor': 'Kidney tumors are abnormal growths in the kidney. They can be benign (non-cancerous) or malignant (cancerous) and may affect kidney function.'
49
  }
50
 
 
 
 
 
 
 
 
 
 
 
 
51
  def preprocess_image(image_path):
 
52
  img = load_img(image_path, target_size=(244, 244))
53
  img_array = img_to_array(img)
54
  img_array = np.expand_dims(img_array, axis=0)
@@ -56,6 +61,7 @@ def preprocess_image(image_path):
56
  return img_array
57
 
58
  def get_prediction(image_path):
 
59
  try:
60
  processed_image = preprocess_image(image_path)
61
  predictions = model.predict(processed_image)
@@ -74,6 +80,7 @@ def get_prediction(image_path):
74
  return None
75
 
76
  def image_to_base64(image_path):
 
77
  with Image.open(image_path) as img:
78
  # Resize the image to be displayed
79
  img.thumbnail((400, 400))
@@ -84,11 +91,12 @@ def image_to_base64(image_path):
84
 
85
  @app.on_event("startup")
86
  async def startup_event():
87
- # Load model on startup
88
  load_kidney_model()
89
 
90
  @app.get("/", response_class=HTMLResponse)
91
  async def index(request: Request):
 
92
  # Check if model is loaded
93
  global model
94
  if model is None:
@@ -103,7 +111,11 @@ async def index(request: Request):
103
 
104
  @app.post("/upload")
105
  async def upload(file: UploadFile = File(...)):
 
106
  if not file:
 
 
 
107
  raise HTTPException(status_code=400, detail="No file selected")
108
 
109
  # Save the file
@@ -118,14 +130,18 @@ async def upload(file: UploadFile = File(...)):
118
  # Convert image to base64 for display
119
  img_base64 = image_to_base64(file_path)
120
  result['image'] = img_base64
121
- return result
122
  else:
123
  raise HTTPException(status_code=500, detail="Prediction failed")
124
 
125
  @app.get("/about", response_class=HTMLResponse)
126
  async def about(request: Request):
 
127
  return templates.TemplateResponse("about.html", {"request": request})
128
 
129
- if __name__ == '__main__':
130
- import uvicorn
131
- uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)
 
 
 
 
1
+ # kidney_fastapi.py
2
+ from fastapi import FastAPI, File, UploadFile, HTTPException
3
+ from fastapi.responses import JSONResponse, HTMLResponse
4
  from fastapi.staticfiles import StaticFiles
5
+ from fastapi.templating import Jinja2Templates
6
+ from fastapi.requests import Request
7
+
8
  import tensorflow as tf
9
  from tensorflow.keras.models import load_model
10
  from tensorflow.keras.preprocessing.image import img_to_array, load_img
 
14
  from io import BytesIO
15
  from PIL import Image
16
  import shutil
17
+ import uvicorn
18
 
19
+ app = FastAPI(title="Kidney Disease Detection",
20
+ description="API for detecting kidney diseases from medical images")
21
 
22
  # Configure upload folder
23
  UPLOAD_FOLDER = 'uploads'
24
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
25
 
26
+ # Configure templates and static files
27
  templates = Jinja2Templates(directory="templates")
 
 
28
  app.mount("/static", StaticFiles(directory="static"), name="static")
29
 
30
+ # Global model variable
31
  model = None
32
 
 
 
 
 
 
 
 
 
 
 
33
  # Define class names based on dataset
34
  class_names = ['Cyst', 'Normal', 'Stone', 'Tumor']
35
 
 
41
  'Tumor': 'Kidney tumors are abnormal growths in the kidney. They can be benign (non-cancerous) or malignant (cancerous) and may affect kidney function.'
42
  }
43
 
44
+ def load_kidney_model():
45
+ """Load the trained kidney disease detection model"""
46
+ global model
47
+ try:
48
+ model = load_model("kidney disease Detection/KIDNEY-Diseases.h5")
49
+ print("Model loaded successfully!")
50
+ return True
51
+ except Exception as e:
52
+ print(f"Error loading model: {e}")
53
+ return False
54
+
55
  def preprocess_image(image_path):
56
+ """Preprocess the image for model prediction"""
57
  img = load_img(image_path, target_size=(244, 244))
58
  img_array = img_to_array(img)
59
  img_array = np.expand_dims(img_array, axis=0)
 
61
  return img_array
62
 
63
  def get_prediction(image_path):
64
+ """Get prediction for an image"""
65
  try:
66
  processed_image = preprocess_image(image_path)
67
  predictions = model.predict(processed_image)
 
80
  return None
81
 
82
  def image_to_base64(image_path):
83
+ """Convert image to base64 for frontend display"""
84
  with Image.open(image_path) as img:
85
  # Resize the image to be displayed
86
  img.thumbnail((400, 400))
 
91
 
92
  @app.on_event("startup")
93
  async def startup_event():
94
+ """Load model when the application starts"""
95
  load_kidney_model()
96
 
97
  @app.get("/", response_class=HTMLResponse)
98
  async def index(request: Request):
99
+ """Render the main page"""
100
  # Check if model is loaded
101
  global model
102
  if model is None:
 
111
 
112
  @app.post("/upload")
113
  async def upload(file: UploadFile = File(...)):
114
+ """Process uploaded image and return prediction"""
115
  if not file:
116
+ raise HTTPException(status_code=400, detail="No file part in the request")
117
+
118
+ if file.filename == "":
119
  raise HTTPException(status_code=400, detail="No file selected")
120
 
121
  # Save the file
 
130
  # Convert image to base64 for display
131
  img_base64 = image_to_base64(file_path)
132
  result['image'] = img_base64
133
+ return JSONResponse(content=result)
134
  else:
135
  raise HTTPException(status_code=500, detail="Prediction failed")
136
 
137
  @app.get("/about", response_class=HTMLResponse)
138
  async def about(request: Request):
139
+ """Render the about page"""
140
  return templates.TemplateResponse("about.html", {"request": request})
141
 
142
+ # Add health check endpoint
143
+ @app.get("/health")
144
+ async def health_check():
145
+ """Health check endpoint"""
146
+ return {"status": "healthy", "model_loaded": model is not None}
147
+