arju10 commited on
Commit
fb31ef1
·
1 Parent(s): 1ac31ca
Files changed (4) hide show
  1. app.ipynb +0 -0
  2. app.py +53 -4
  3. food_model.pkl → model.pth +2 -2
  4. recognizer_image.py +152 -0
app.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
app.py CHANGED
@@ -31,10 +31,59 @@
31
 
32
 
33
 
 
 
 
 
 
 
 
 
 
 
 
34
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- def greet(name):
37
- return "Hello " + name + "!!"
 
 
 
 
 
 
 
38
 
39
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
40
- iface.launch()
 
31
 
32
 
33
 
34
+ # import gradio as gr
35
+
36
+ # def greet(name):
37
+ # return "Hello " + name + "!!"
38
+
39
+ # iface = gr.Interface(fn=greet, inputs="text", outputs="text")
40
+ # iface.launch()
41
+
42
+
43
+
44
+ """Step 7: Deploying on Hugging Face Model Hub"""
45
  import gradio as gr
46
+ import torch
47
+
48
+ # Load the saved model from .pkl file
49
+ model = torch.load("model.pth")
50
+
51
+ # !pip install transformers
52
+
53
+ # Define the preprocessing function
54
+ preprocess = transforms.Compose([
55
+ transforms.Resize(224),
56
+ transforms.CenterCrop(224),
57
+ transforms.ToTensor(),
58
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
59
+ ])
60
+
61
+ # Define the predict function
62
+ def predict_food_image(image):
63
+ # Preprocess the input image
64
+ img = Image.fromarray(image.astype('uint8'), 'RGB')
65
+ img = preprocess(img)
66
+ img = img.unsqueeze(0)
67
+
68
+ # Run the model prediction
69
+ with torch.no_grad():
70
+ outputs = model(img)
71
+
72
+ # Post-process the outputs
73
+ predicted_class = torch.argmax(outputs).item()
74
+
75
+ # Return the predicted category
76
+ return predicted_class
77
 
78
+ # Define the Gradio interface
79
+ gr_interface = gr.Interface(
80
+ fn=predict_food_image,
81
+ inputs="image",
82
+ outputs="text",
83
+ title="Food Image Recognizer",
84
+ description="Upload an image of food and get the predicted category.",
85
+ allow_flagging=False
86
+ )
87
 
88
+ # Launch the interface
89
+ gr_interface.launch(share=True)
food_model.pkl → model.pth RENAMED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7b69eda976f7f38dfd369c21687943b70da604bb1c79e094983e3ebf2e341900
3
- size 87509175
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:13ab178215e7cf49cd23173527cbaaeb10c7e7c160087b9a07c0e164cdfefb53
3
+ size 262001181
recognizer_image.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """recognizer_image.ipynb
3
+
4
+ Automatically generated by Colaboratory.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1gRejGB4T2LDDXPQNTKBXJUahCXt2vA_G
8
+
9
+ Step 1: Install the required libraries
10
+ """
11
+
12
+ # !pip install torch torchvision
13
+ # !pip install fastai==2.5.2
14
+ # !pip install fastbook==0.0.16
15
+
16
+ """Step 2: Import the necessary libraries"""
17
+
18
+ from fastai.vision.all import *
19
+ from fastbook import *
20
+
21
+ # """Step 3: Mount Google Drive"""
22
+
23
+ # from google.colab import drive
24
+
25
+ # # Mount Google Drive
26
+ # drive.mount('/content/drive')
27
+
28
+ """Step 4: Set the data path"""
29
+
30
+ data_path = '/content/drive/MyDrive/Master_Course_Data Science/Capstone_Project/foods_images'
31
+
32
+ """Step 5: Define data augmentation and data block"""
33
+
34
+ data_augmentation = aug_transforms(mult=1.0, flip_vert=True, max_zoom=1.1, max_rotate=20.0, max_lighting=0.4)
35
+
36
+ try:
37
+ food_dblock = DataBlock(
38
+ blocks=(ImageBlock, CategoryBlock),
39
+ get_items=get_image_files,
40
+ splitter=RandomSplitter(valid_pct=0.2, seed=42),
41
+ get_y=parent_label,
42
+ item_tfms=Resize(224),
43
+ batch_tfms=[*data_augmentation, Normalize.from_stats(*imagenet_stats)]
44
+ )
45
+ except Exception as e:
46
+ print(f"Error in defining the data block: {e}")
47
+ sys.exit(1)
48
+
49
+ """Step 6: Create dataloaders"""
50
+
51
+ try:
52
+ dls = food_dblock.dataloaders(data_path)
53
+ except Exception as e:
54
+ print(f"Error in creating dataloaders: {e}")
55
+ sys.exit(1)
56
+
57
+ """Step 7: Show a batch of images"""
58
+
59
+ try:
60
+ dls.show_batch()
61
+ except Exception as e:
62
+ print(f"Error in showing batch of images: {e}")
63
+ sys.exit(1)
64
+
65
+ """Step 8: Train the model"""
66
+
67
+ learn = cnn_learner(dls, resnet34, metrics=accuracy)
68
+ try:
69
+ learn.fine_tune(4)
70
+ except Exception as e:
71
+ print(f"Error in fine-tuning the model: {e}")
72
+ sys.exit(1)
73
+
74
+ learn.save("/content/drive/MyDrive/Master_Course_Data Science/Capstone_Project/model")
75
+
76
+ # !pip install gradio
77
+
78
+
79
+ import gradio as gr
80
+
81
+ from torchvision.transforms import transforms
82
+ from PIL import Image
83
+
84
+ # Define the prediction function
85
+ def predict_food_image(img):
86
+ pred = learn.predict(img)[0]
87
+ return str(pred)
88
+
89
+ # Create the Gradio interface
90
+ gr_interface = gr.Interface(
91
+ fn=predict_food_image,
92
+ inputs="image",
93
+ outputs="text",
94
+ title="Food Image Recognizer",
95
+ description="Upload an image of food and get the predicted category.",
96
+ allow_flagging=False
97
+ )
98
+
99
+ # Launch the interface
100
+ gr_interface.launch(share=True)
101
+
102
+ """Step 7: Deploying on Hugging Face Model Hub"""
103
+
104
+ import torch
105
+
106
+ # Load the saved model from .pkl file
107
+ model = torch.load("/content/drive/MyDrive/Master_Course_Data Science/Capstone_Project/model.pth")
108
+
109
+ # !pip install transformers
110
+
111
+ # Define the preprocessing function
112
+ preprocess = transforms.Compose([
113
+ transforms.Resize(224),
114
+ transforms.CenterCrop(224),
115
+ transforms.ToTensor(),
116
+ transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
117
+ ])
118
+
119
+ # Define the predict function
120
+ def predict_food_image(image):
121
+ # Preprocess the input image
122
+ img = Image.fromarray(image.astype('uint8'), 'RGB')
123
+ img = preprocess(img)
124
+ img = img.unsqueeze(0)
125
+
126
+ # Run the model prediction
127
+ with torch.no_grad():
128
+ outputs = model(img)
129
+
130
+ # Post-process the outputs
131
+ predicted_class = torch.argmax(outputs).item()
132
+
133
+ # Return the predicted category
134
+ return predicted_class
135
+
136
+ # Define the Gradio interface
137
+ gr_interface = gr.Interface(
138
+ fn=predict_food_image,
139
+ inputs="image",
140
+ outputs="text",
141
+ title="Food Image Recognizer",
142
+ description="Upload an image of food and get the predicted category.",
143
+ allow_flagging=False
144
+ )
145
+
146
+ # Launch the interface
147
+ gr_interface.launch(share=True)
148
+
149
+ """Notebook to Python Script Export"""
150
+
151
+ !pip uninstall nbdev
152
+ !pip install nbdev==1.1.13