sharktide commited on
Commit
e10a731
·
1 Parent(s): ce9ad9e

Add logic for app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -4
app.py CHANGED
@@ -1,7 +1,40 @@
1
- from fastapi import FastAPI
 
 
 
 
 
2
 
 
 
 
 
 
 
 
3
  app = FastAPI()
4
 
5
- @app.get("/")
6
- def greet_json():
7
- return {"Hello": "World!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile
2
+ import tensorflow as tf
3
+ import numpy as np
4
+ from PIL import Image
5
+ from io import BytesIO
6
+ from fastapi.responses import JSONResponse
7
 
8
+ # Load your trained model (make sure it's available in the working directory)
9
+ model = tf.keras.models.load_model('model.h5')
10
+
11
+ # Class names for predictions (modify if necessary)
12
+ class_names = ['Glass', 'Metal', 'Paperboard', 'Plastic-Polystyrene', 'Plastic-Regular']
13
+
14
+ # Create FastAPI app
15
  app = FastAPI()
16
 
17
+ # Preprocessing the image (resize, normalize, etc.)
18
+ def preprocess_image(image_file):
19
+ image = Image.open(image_file)
20
+ image = image.resize((240, 240)) # Resize image to match model input
21
+ img_array = np.array(image) # Convert to numpy array
22
+ img_array = img_array.astype(np.float32) / 255.0 # Normalize
23
+ img_array = np.expand_dims(img_array, axis=0) # Add batch dimension
24
+ return img_array
25
+
26
+ @app.post("/predict")
27
+ async def predict(file: UploadFile = File(...)):
28
+ try:
29
+ img_array = preprocess_image(file.file)
30
+ predictions = model.predict(img_array)
31
+ predicted_class_idx = np.argmax(predictions, axis=1)[0]
32
+ predicted_class = class_names[predicted_class_idx]
33
+ return JSONResponse(content={"prediction": predicted_class})
34
+ except Exception as e:
35
+ return JSONResponse(content={"error": str(e)}, status_code=400)
36
+
37
+ # If you want to manually run FastAPI (though Hugging Face will typically do this)
38
+ if __name__ == "__main__":
39
+ import uvicorn
40
+ uvicorn.run(app, host="0.0.0.0", port=7860)