salek877 commited on
Commit
8e22f7f
·
1 Parent(s): 09961ea

main api file

Browse files
Files changed (1) hide show
  1. main.py +46 -0
main.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile
2
+ from starlette.middleware.cors import CORSMiddleware
3
+ from PIL import Image
4
+ import tensorflow as tf
5
+ import numpy as np
6
+ import io
7
+
8
+
9
+ app = FastAPI()
10
+ # Enable CORS to allow cross-origin requests
11
+ app.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=["*"],
14
+ allow_methods=["*"],
15
+ allow_headers=["*"],
16
+ )
17
+
18
+ # Load the Coffee Land Classifier model
19
+ model_path = "model/model.h5"
20
+ class_labels = ["Coffee Land", "Not Coffee Land"]
21
+ model = tf.keras.models.load_model(model_path, compile=False)
22
+
23
+ def preprocess_image(image):
24
+ # Resize and preprocess the image
25
+ img = image.resize((64, 64))
26
+ img = np.array(img)
27
+ img = img.astype('float32') / 255.0
28
+ img = np.expand_dims(img, axis=0)
29
+ return img
30
+
31
+ def predict_class(image):
32
+ img = preprocess_image(image)
33
+ predictions = model.predict(img)
34
+ class_index = np.argmax(predictions)
35
+ predicted_class = class_labels[class_index]
36
+ return predicted_class, predictions[0].tolist()
37
+
38
+ @app.post("/predict/")
39
+ async def predict(upload_file: UploadFile = File(...)):
40
+ file_contents = await upload_file.read() # Use upload_file, not request.file
41
+ print(f"Received file with size: {len(file_contents)} bytes")
42
+ image = Image.open(io.BytesIO(file_contents))
43
+ predicted_class, class_probabilities = predict_class(image)
44
+ return {"predicted_class": predicted_class, "class_probabilities": class_probabilities}
45
+
46
+