Yumeng Liu commited on
Commit
5b92a5a
·
1 Parent(s): f594744

image processing and prediction

Browse files
Files changed (2) hide show
  1. app.py +27 -4
  2. requirements.txt +1 -1
app.py CHANGED
@@ -1,15 +1,30 @@
1
- # import keras
 
 
 
 
2
  import fastapi
3
  from fastapi import UploadFile, File, HTTPException
4
  from PIL import Image
5
  import io
6
  import time
 
 
7
 
8
  app = fastapi.FastAPI()
9
 
10
- # model = keras.saving.load_model("hf://Yumeng-Liu/trash-classifier")
 
11
 
12
- print("Started")
 
 
 
 
 
 
 
 
13
 
14
 
15
  @app.get("/")
@@ -24,11 +39,18 @@ async def predict(received_image: UploadFile = File(...)):
24
  # Open the binary data as an image
25
  image = Image.open(io.BytesIO(contents))
26
 
 
27
  # You can now work with the `image` object
28
  print(image.format, image.size, image.mode) # Example: JPEG (1920, 1080) RGB
 
 
 
 
29
 
30
  # Perform further processing, e.g., save it, analyze it, etc.
31
- return {"filename": received_image.filename, "message": "Image processed successfully"}
 
 
32
 
33
  except Exception as e:
34
  print(e)
@@ -39,5 +61,6 @@ async def predict(received_image: UploadFile = File(...)):
39
 
40
 
41
  if __name__ == "__main__":
 
42
  while True:
43
  time.sleep(10)
 
1
+ from keras import (
2
+ saving,
3
+ preprocessing,
4
+ applications
5
+ )
6
  import fastapi
7
  from fastapi import UploadFile, File, HTTPException
8
  from PIL import Image
9
  import io
10
  import time
11
+ import numpy as np
12
+
13
 
14
  app = fastapi.FastAPI()
15
 
16
+ model = saving.load_model("hf://Yumeng-Liu/trash-classifier")
17
+
18
 
19
+ def get_prediction(img: Image):
20
+ img = img.resize((224, 224))
21
+ img = img.convert("L")
22
+ img_array = preprocessing.image.img_to_array(img)
23
+ img_array = np.expand_dims(img_array, axis=0) # Add an extra dimension to match the model's input shape
24
+ img_array = applications.mobilenet_v2.preprocess_input(img_array)
25
+
26
+ prediction = model.predict(img_array)
27
+ return prediction
28
 
29
 
30
  @app.get("/")
 
39
  # Open the binary data as an image
40
  image = Image.open(io.BytesIO(contents))
41
 
42
+ print("Image received")
43
  # You can now work with the `image` object
44
  print(image.format, image.size, image.mode) # Example: JPEG (1920, 1080) RGB
45
+ print("")
46
+
47
+ prediction_result = get_prediction(image)
48
+ print(prediction_result)
49
 
50
  # Perform further processing, e.g., save it, analyze it, etc.
51
+ return {
52
+ "result": prediction_result
53
+ }
54
 
55
  except Exception as e:
56
  print(e)
 
61
 
62
 
63
  if __name__ == "__main__":
64
+ print("Starting app")
65
  while True:
66
  time.sleep(10)
requirements.txt CHANGED
@@ -4,4 +4,4 @@ tensorflow
4
  keras
5
  huggingface_hub
6
  python-multipart
7
- pillow
 
4
  keras
5
  huggingface_hub
6
  python-multipart
7
+ pillow