Ashok-space commited on
Commit
dbad4f7
·
verified ·
1 Parent(s): 0a180c1

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +41 -0
main.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile
2
+ from fastapi.responses import JSONResponse
3
+ import tensorflow as tf
4
+ import numpy as np
5
+ import pickle
6
+ from PIL import Image
7
+ import io
8
+
9
+ app = FastAPI()
10
+
11
+ # Load model and encoder
12
+ model = tf.keras.models.load_model("best_sleeve_model.keras")
13
+ with open("sleeve_length_encoder.pkl", "rb") as f:
14
+ encoder = pickle.load(f)
15
+
16
+ # Define image preprocessing function
17
+ def preprocess_image(image_bytes):
18
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
19
+ image = image.resize((224, 224)) # Change this if your model expects a different size
20
+ image_array = np.array(image) / 255.0 # Normalize if your model was trained that way
21
+ image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
22
+ return image_array
23
+
24
+ @app.get("/")
25
+ def root():
26
+ return {"message": "Sleeve Length Image Prediction API is running."}
27
+
28
+ @app.post("/predict")
29
+ async def predict(file: UploadFile = File(...)):
30
+ try:
31
+ image_bytes = await file.read()
32
+ input_tensor = preprocess_image(image_bytes)
33
+
34
+ # Make prediction
35
+ prediction = model.predict(input_tensor)
36
+ class_index = np.argmax(prediction, axis=1)
37
+ label = encoder.inverse_transform(class_index)
38
+
39
+ return JSONResponse(content={"sleeve_length": label[0]})
40
+ except Exception as e:
41
+ return JSONResponse(content={"error": str(e)}, status_code=500)