gruhit-patel commited on
Commit
071870f
1 Parent(s): e189f90

Transferred from from PyTorch -> Tensorflow

Browse files
Files changed (4) hide show
  1. Dockerfile +1 -1
  2. backend.py +45 -72
  3. model.py +36 -52
  4. requirements.txt +7 -8
Dockerfile CHANGED
@@ -1,5 +1,5 @@
1
  # Get the image of python
2
- FROM python:3.9
3
 
4
  # Copy all the files from local-dir to machine dir
5
  COPY . .
 
1
  # Get the image of python
2
+ FROM python:3.7.9
3
 
4
  # Copy all the files from local-dir to machine dir
5
  COPY . .
backend.py CHANGED
@@ -1,90 +1,63 @@
 
 
1
 
2
- from model import get_model
3
-
4
- import torch as T
5
- import torch.nn.functional as F
6
- from torchvision.transforms import v2
7
  from fastapi import FastAPI, UploadFile, File
8
-
9
-
10
  import json
11
- import numpy as np
12
  from PIL import Image
13
  from io import BytesIO
14
 
15
- MODEL_IMAGE_WIDTH = 224
16
- MODEL_IMAGE_HEIGHT = 224
 
 
 
 
17
 
18
- transform = v2.Compose([
19
- v2.Resize((MODEL_IMAGE_HEIGHT, MODEL_IMAGE_WIDTH)),
20
- v2.ToTensor()
21
- ])
 
 
 
 
22
 
23
  ######### Utilities #########
24
  def load_image(image_data):
25
- image = Image.open(BytesIO(image_data))
26
- return image
27
 
28
  def preprocess(image):
29
- image = image.resize((MODEL_IMAGE_WIDTH, MODEL_IMAGE_HEIGHT))
30
- image = transform(image)
31
-
32
- return image
33
-
34
- def get_prediction(image, model):
35
- image = T.from_numpy(np.array(image))
36
- print("image shape: ", image.shape)
37
-
38
- image = image.unsqueeze(0)
39
- # image = image.permute(0, 3, 1, 2)
40
- print("batch size shape: ", image.shape)
41
-
42
- pred_probs = model(image)
43
- pred_probs = F.softmax(pred_probs, dim=-1)
44
- pred_probs = pred_probs.detach().numpy()[0]
45
- label = np.argmax(pred_probs, axis=-1)
46
-
47
- return {
48
- 'pred_probs': pred_probs.tolist(),
49
- 'label': int(label)
50
- }
51
-
52
- ####################################
53
-
54
- ############## Backend #############
55
- app = FastAPI()
56
- model = T.jit.load('model_script.pt')
57
 
58
  @app.get("/")
59
  def foo():
60
- return {
61
- "status": "Face Expression Classifier"
62
- }
63
 
64
- @app.post("/")
65
- def bar():
66
- return {
67
- "status": "Response"
68
- }
69
 
70
  @app.post("/get_prediction")
71
- async def predict(face_img: UploadFile = File(...)):
72
- image = load_image(await face_img.read())
73
-
74
- image = preprocess(image)
75
-
76
- result = get_prediction(image, model)
77
- print("Model Predicted: \n", result)
78
-
79
- return {
80
- 'result': json.dumps(result)
81
- }
82
-
83
- @app.post("/test")
84
- def test():
85
- return {
86
- 'result': {
87
- 'pred_probs': [0.5, 0.2, 0.1],
88
- 'label': 0
89
- }
90
- }
 
1
+ import os
2
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
3
 
 
 
 
 
 
4
  from fastapi import FastAPI, UploadFile, File
 
 
5
  import json
 
6
  from PIL import Image
7
  from io import BytesIO
8
 
9
+ from model import get_model
10
+
11
+ app = FastAPI()
12
+
13
+ IMAGE_WIDTH = 224
14
+ IMAGE_HEIGHT = 224
15
 
16
+ MODEL_WEIGHT_PATH = 'vgg_face_weights2.h5'
17
+ model = get_model(
18
+ image_shape = (IMAGE_WIDTH, IMAGE_HEIGHT, 3),
19
+ num_classes = 6,
20
+ model_weights = MODEL_WEIGHT_PATH
21
+ )
22
+ print(model.summary())
23
+ print("Model Loaded Successfully")
24
 
25
  ######### Utilities #########
26
  def load_image(image_data):
27
+ image = Image.open(BytesIO(image_data))
28
+ return image
29
 
30
  def preprocess(image):
31
+ image = image.resize((IMAGE_WIDTH, IMAGE_HEIGHT))
32
+
33
+ image = np.array(image)
34
+ image = np.expand_dims(image, axis=0)
35
+
36
+ return image
37
+
38
+ def get_prediction(image):
39
+ probs = model.predict(image)[0]
40
+ label = np.argmax(probs)
41
+
42
+ return {
43
+ 'pred_probs': pred_probs.tolist(),
44
+ 'label': int(label)
45
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
  @app.get("/")
48
  def foo():
49
+ return {
50
+ "status": "Face Expression Classifier"
51
+ }
52
 
 
 
 
 
 
53
 
54
  @app.post("/get_prediction")
55
+ async def predict(face_image: UploadFile = File(...)):
56
+ image = load_image(await face_image.read())
57
+
58
+ image = preprocess(image)
59
+ result = get_prediction(image)
60
+
61
+ return {
62
+ "result": json.dumps(result)
63
+ }
 
 
 
 
 
 
 
 
 
 
 
model.py CHANGED
@@ -1,55 +1,39 @@
1
- import torch as T
2
- from torch import nn, optim
3
- import torch.nn.functional as F
4
- import torchvision.models as models
5
-
6
- from typing import Union, List
7
-
8
- def get_model(num_classes:int, unfreeze_layers:Union[None, List[int]] = None, drop_rate: Union[None, float] = None):
9
-
10
- model = models.efficientnet_b7(weights=models.EfficientNet_B7_Weights.DEFAULT)
11
-
12
-
13
-
14
- for param in model.parameters():
15
-
16
- param.requires_grad = False
17
-
18
-
19
-
20
- if unfreeze_layers is not None and len(unfreeze_layers) > 0:
21
-
22
- # Now unfreeze the layers in the unfreeze layer/ list
23
-
24
- for layer_num in unfreeze_layers:
25
-
26
- for name, child in model.features[layer_num].named_modules():
27
-
28
- if not isinstance(child, nn.BatchNorm2d) and \
29
- not isinstance(child, nn.Sequential) and \
30
- not hasattr(child, 'block'):
31
-
32
- for param in child.parameters():
33
-
34
- param.requires_grad = True
35
-
36
-
37
-
38
- if drop_rate is not None:
39
-
40
- model.classifier[0] = nn.Dropout(drop_rate)
41
-
42
-
43
-
44
- # Chagne the classifier head as per our need
45
-
46
- model.classifier[1] = nn.Linear(2560, num_classes)
47
-
48
  return model
49
 
 
50
  if __name__ == "__main__":
51
- model = get_model(
52
- 6,
53
- [-1],
54
- 0.1
55
- )
 
 
 
 
1
+ import os
2
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
3
+
4
+ import keras
5
+ from keras.layers import Input, Dropout, Dense
6
+ from keras.models import Model
7
+ from keras_vggface.vggface import VGGFace
8
+
9
+ def get_model(image_shape, num_classes, model_weights, unfreeze_layers=-3, drop_rate=0.5):
10
+
11
+ input_layer = Input(shape=image_shape)
12
+ vgg_base_model = VGGFace(include_top = False, input_shape = image_shape, pooling='avg')
13
+
14
+ # Freeze all the layers till unfreeze layers
15
+ for layer in vgg_base_model.layers[:unfreeze_layers]:
16
+ layer.trainable = False
17
+
18
+ for layer in vgg_base_model.layers[unfreeze_layers:]:
19
+ layer.trainable = True
20
+
21
+ x = vgg_base_model(input_layer)
22
+
23
+ x = Dropout(drop_rate)(x)
24
+ output = Dense(num_classes, activation='softmax')(x)
25
+
26
+ model = Model(inputs=[input_layer], outputs=[output], name="Expression_Classifier")
27
+ model.load_weights(model_weights)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  return model
29
 
30
+
31
  if __name__ == "__main__":
32
+ model_path = "vgg_face_weights2.h5"
33
+ model = get_model(
34
+ image_shape = (224, 224, 3),
35
+ num_classes = 6,
36
+ model_weights = model_path
37
+ )
38
+
39
+ print(model.summary())
requirements.txt CHANGED
@@ -1,8 +1,7 @@
1
- streamlit
2
- fastapi
3
- uvicorn[standard]
4
- torch==2.3.1
5
- torchaudio==2.3.1
6
- torchvision==0.18.1
7
- pillow
8
- numpy
 
1
+ keras==2.2.4
2
+ keras_vggface==0.6
3
+ tensorflow==1.14.0
4
+ protobuf==3.20.1
5
+ h5py==2.10.0
6
+ fastapi==0.103.2
7
+ uvicorn[standard]