Ahmed007 commited on
Commit
4f87d63
1 Parent(s): 0a9a7a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -4
app.py CHANGED
@@ -1,8 +1,57 @@
 
 
 
 
 
 
 
 
1
 
2
- from fastapi import FastAPI
 
3
 
 
4
  app = FastAPI()
5
 
6
- @app.get("/")
7
- def greet_json():
8
- return {"Hello": "World!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, HTTPException
2
+ from fastapi.responses import JSONResponse
3
+ from tensorflow.keras.models import load_model
4
+ from tensorflow.keras.preprocessing import image
5
+ import numpy as np
6
+ import logging
7
+ from PIL import Image
8
+ import io
9
 
10
+ # Configure logging
11
+ logging.basicConfig(level=logging.DEBUG)
12
 
13
+ # Initialize FastAPI app
14
  app = FastAPI()
15
 
16
+ # Load your trained model
17
+ model = load_model('model.h5')
18
+ class_names = ['Normal', 'bacteria', 'virus']
19
+
20
+ def preprocess_image(img, target_size):
21
+ """Resize and preprocess the image for the model."""
22
+ if img.mode != "RGB":
23
+ img = img.convert("RGB")
24
+ img = img.resize(target_size)
25
+ img_array = image.img_to_array(img)
26
+ img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
27
+ return img_array
28
+
29
+ @app.post("/predict")
30
+ async def predict(file: UploadFile = File(...)):
31
+ if not file:
32
+ raise HTTPException(status_code=400, detail="No file provided")
33
+ try:
34
+ # Read the file's content into a BytesIO object
35
+ img_bytes = io.BytesIO(await file.read())
36
+
37
+ # Use PIL to open the image
38
+ img = Image.open(img_bytes)
39
+ img_array = preprocess_image(img, (224, 224))
40
+
41
+ # Make prediction
42
+ predictions = model.predict(img_array)
43
+
44
+ predicted_class = np.argmax(predictions, axis=1)
45
+
46
+ # Return the prediction
47
+ predictions = {
48
+ 'class': class_names[predicted_class[0]],
49
+ 'confidence': float(predictions[0][predicted_class[0]])
50
+ }
51
+ return JSONResponse(content=predictions)
52
+ except Exception as e:
53
+ logging.debug(f"Error processing the file: {str(e)}")
54
+ raise HTTPException(status_code=500, detail=f"Error processing the file: {str(e)}")
55
+
56
+ if __name__ == '__main__':
57
+ app.run()