MuhammmadRizwanRizwan commited on
Commit
9f80c53
·
verified ·
1 Parent(s): 76c62bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -148
app.py CHANGED
@@ -16,171 +16,171 @@
16
 
17
 
18
 
19
- # import streamlit as st
20
- # from tensorflow.keras.models import load_model
21
- # from tensorflow.keras.preprocessing import image
22
- # import numpy as np
23
- # from PIL import Image
24
 
25
- # # Load the pre-trained models
26
- # @st.cache_resource
27
- # def load_models():
28
- # model1 = load_model('name_model_inception.h5') # Update with your Hugging Face model path
29
- # model2 = load_model('type_model_inception.h5') # Update with your Hugging Face model path
30
- # return model1, model2
31
 
32
- # model1, model2 = load_models()
33
 
34
- # # Label mappings
35
- # label_map1 = {
36
- # 0: "Banana", 1: "Cucumber", 2: "Grape", 3: "Kaki", 4: "Papaya",
37
- # 5: "Peach", 6: "Pear", 7: "Pepper", 8: "Strawberry", 9: "Watermelon", 10: "Tomato"
38
- # }
39
 
40
- # label_map2 = {
41
- # 0: "Good", 1: "Mild", 2: "Rotten"
42
- # }
43
 
44
- # # Streamlit app layout
45
- # st.title("Fruit Classifier")
46
 
47
- # # Upload image
48
- # uploaded_file = st.file_uploader("Choose an image of a fruit", type=["jpg", "jpeg", "png"])
49
 
50
- # if uploaded_file is not None:
51
- # # Display the uploaded image
52
- # img = Image.open(uploaded_file)
53
- # st.image(img, caption="Uploaded Image", use_column_width=True)
54
 
55
- # # Preprocess the image
56
- # img = img.resize((224, 224)) # Resize image to match the model input
57
- # img_array = image.img_to_array(img)
58
- # img_array = np.expand_dims(img_array, axis=0)
59
- # img_array = img_array / 255.0 # Normalize the image
60
 
61
- # # Make predictions
62
- # pred1 = model1.predict(img_array)
63
- # pred2 = model2.predict(img_array)
64
 
65
- # predicted_class1 = np.argmax(pred1, axis=1)
66
- # predicted_class2 = np.argmax(pred2, axis=1)
67
 
68
- # # Display results
69
- # st.write(f"**Type Detection**: {label_map1[predicted_class1[0]]}")
70
- # st.write(f"**Condition Detection**: {label_map2[predicted_class2[0]]}")
71
 
72
 
73
 
74
 
75
- !git clone 'https://github.com/facebookresearch/detectron2'
76
- dist = distutils.core.run_setup("./detectron2/setup.py")
77
- !python -m pip install {' '.join([f"'{x}'" for x in dist.install_requires])}
78
- sys.path.insert(0, os.path.abspath('./detectron2'))
79
 
80
 
81
 
82
- import streamlit as st
83
- import numpy as np
84
- import cv2
85
- import warnings
86
-
87
- # Suppress warnings
88
- warnings.filterwarnings("ignore", category=FutureWarning)
89
- warnings.filterwarnings("ignore", category=UserWarning)
90
-
91
- # Try importing TensorFlow
92
- try:
93
- from tensorflow.keras.models import load_model
94
- from tensorflow.keras.preprocessing import image
95
- except ImportError:
96
- st.error("Failed to import TensorFlow. Please make sure it's installed correctly.")
97
-
98
- # Try importing PyTorch and Detectron2
99
- try:
100
- import torch
101
- from detectron2.engine import DefaultPredictor
102
- from detectron2.config import get_cfg
103
- from detectron2.utils.visualizer import Visualizer
104
- from detectron2.data import MetadataCatalog
105
- except ImportError:
106
- st.error("Failed to import PyTorch or Detectron2. Please make sure they're installed correctly.")
107
-
108
- # Load the trained models
109
- try:
110
- model_path_name = 'name_model_inception.h5'
111
- model_path_quality = 'type_model_inception.h5'
112
- detectron_config_path = 'watermelon.yaml'
113
- detectron_weights_path = 'Watermelon_model.pth'
114
-
115
- model_name = load_model(model_path_name)
116
- model_quality = load_model(model_path_quality)
117
- except Exception as e:
118
- st.error(f"Failed to load models: {str(e)}")
119
-
120
- # Streamlit app title
121
- st.title("Watermelon Quality and Damage Detection")
122
 
123
- # Upload image
124
- uploaded_file = st.file_uploader("Choose a watermelon image...", type=["jpg", "jpeg", "png"])
125
 
126
- if uploaded_file is not None:
127
- try:
128
- # Load the image
129
- img = image.load_img(uploaded_file, target_size=(224, 224))
130
- img_array = image.img_to_array(img)
131
- img_array = np.expand_dims(img_array, axis=0)
132
- img_array /= 255.0
133
-
134
- # Display uploaded image
135
- st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
136
-
137
- # Predict watermelon name
138
- pred_name = model_name.predict(img_array)
139
- predicted_name = 'Watermelon'
140
-
141
- # Predict watermelon quality
142
- pred_quality = model_quality.predict(img_array)
143
- predicted_class_quality = np.argmax(pred_quality, axis=1)
144
-
145
- # Define labels for watermelon quality
146
- label_map_quality = {
147
- 0: "Good",
148
- 1: "Mild",
149
- 2: "Rotten"
150
- }
151
-
152
- predicted_quality = label_map_quality[predicted_class_quality[0]]
153
-
154
- # Display predictions
155
- st.write(f"Fruit Type Detection: {predicted_name}")
156
- st.write(f"Fruit Quality Classification: {predicted_quality}")
157
-
158
- # If the quality is 'Mild' or 'Rotten', pass the image to the mask detection model
159
- if predicted_quality in ["Mild", "Rotten"]:
160
- st.write("Passing the image to the mask detection model for damage detection...")
161
-
162
- # Load the image again for the mask detection (Detectron2 requires the original image)
163
- im = cv2.imdecode(np.fromstring(uploaded_file.read(), np.uint8), 1)
164
-
165
- # Setup Detectron2 configuration for watermelon
166
- cfg = get_cfg()
167
- cfg.merge_from_file(detectron_config_path)
168
- cfg.MODEL.WEIGHTS = detectron_weights_path
169
- cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
170
- cfg.MODEL.DEVICE = 'cpu' # Use CPU for inference
171
-
172
- predictor = DefaultPredictor(cfg)
173
- predictor.model.load_state_dict(torch.load(detectron_weights_path, map_location=torch.device('cpu')))
174
-
175
- # Run prediction on the image
176
- outputs = predictor(im)
177
-
178
- # Visualize the predictions
179
- v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8)
180
- out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
181
-
182
- # Display the output
183
- st.image(out.get_image()[:, :, ::-1], caption="Detected Damage", use_column_width=True)
184
-
185
- except Exception as e:
186
- st.error(f"An error occurred during processing: {str(e)}")
 
16
 
17
 
18
 
19
+ import streamlit as st
20
+ from tensorflow.keras.models import load_model
21
+ from tensorflow.keras.preprocessing import image
22
+ import numpy as np
23
+ from PIL import Image
24
 
25
+ # Load the pre-trained models
26
+ @st.cache_resource
27
+ def load_models():
28
+ model1 = load_model('name_model_inception.h5') # Update with your Hugging Face model path
29
+ model2 = load_model('type_model_inception.h5') # Update with your Hugging Face model path
30
+ return model1, model2
31
 
32
+ model1, model2 = load_models()
33
 
34
+ # Label mappings
35
+ label_map1 = {
36
+ 0: "Banana", 1: "Cucumber", 2: "Grape", 3: "Kaki", 4: "Papaya",
37
+ 5: "Peach", 6: "Pear", 7: "Pepper", 8: "Strawberry", 9: "Watermelon", 10: "Tomato"
38
+ }
39
 
40
+ label_map2 = {
41
+ 0: "Good", 1: "Mild", 2: "Rotten"
42
+ }
43
 
44
+ # Streamlit app layout
45
+ st.title("Fruit Classifier")
46
 
47
+ # Upload image
48
+ uploaded_file = st.file_uploader("Choose an image of a fruit", type=["jpg", "jpeg", "png"])
49
 
50
+ if uploaded_file is not None:
51
+ # Display the uploaded image
52
+ img = Image.open(uploaded_file)
53
+ st.image(img, caption="Uploaded Image", use_column_width=True)
54
 
55
+ # Preprocess the image
56
+ img = img.resize((224, 224)) # Resize image to match the model input
57
+ img_array = image.img_to_array(img)
58
+ img_array = np.expand_dims(img_array, axis=0)
59
+ img_array = img_array / 255.0 # Normalize the image
60
 
61
+ # Make predictions
62
+ pred1 = model1.predict(img_array)
63
+ pred2 = model2.predict(img_array)
64
 
65
+ predicted_class1 = np.argmax(pred1, axis=1)
66
+ predicted_class2 = np.argmax(pred2, axis=1)
67
 
68
+ # Display results
69
+ st.write(f"**Type Detection**: {label_map1[predicted_class1[0]]}")
70
+ st.write(f"**Condition Detection**: {label_map2[predicted_class2[0]]}")
71
 
72
 
73
 
74
 
75
+ # !git clone 'https://github.com/facebookresearch/detectron2'
76
+ # dist = distutils.core.run_setup("./detectron2/setup.py")
77
+ # !python -m pip install {' '.join([f"'{x}'" for x in dist.install_requires])}
78
+ # sys.path.insert(0, os.path.abspath('./detectron2'))
79
 
80
 
81
 
82
+ # import streamlit as st
83
+ # import numpy as np
84
+ # import cv2
85
+ # import warnings
86
+
87
+ # # Suppress warnings
88
+ # warnings.filterwarnings("ignore", category=FutureWarning)
89
+ # warnings.filterwarnings("ignore", category=UserWarning)
90
+
91
+ # # Try importing TensorFlow
92
+ # try:
93
+ # from tensorflow.keras.models import load_model
94
+ # from tensorflow.keras.preprocessing import image
95
+ # except ImportError:
96
+ # st.error("Failed to import TensorFlow. Please make sure it's installed correctly.")
97
+
98
+ # # Try importing PyTorch and Detectron2
99
+ # try:
100
+ # import torch
101
+ # from detectron2.engine import DefaultPredictor
102
+ # from detectron2.config import get_cfg
103
+ # from detectron2.utils.visualizer import Visualizer
104
+ # from detectron2.data import MetadataCatalog
105
+ # except ImportError:
106
+ # st.error("Failed to import PyTorch or Detectron2. Please make sure they're installed correctly.")
107
+
108
+ # # Load the trained models
109
+ # try:
110
+ # model_path_name = 'name_model_inception.h5'
111
+ # model_path_quality = 'type_model_inception.h5'
112
+ # detectron_config_path = 'watermelon.yaml'
113
+ # detectron_weights_path = 'Watermelon_model.pth'
114
+
115
+ # model_name = load_model(model_path_name)
116
+ # model_quality = load_model(model_path_quality)
117
+ # except Exception as e:
118
+ # st.error(f"Failed to load models: {str(e)}")
119
+
120
+ # # Streamlit app title
121
+ # st.title("Watermelon Quality and Damage Detection")
122
 
123
+ # # Upload image
124
+ # uploaded_file = st.file_uploader("Choose a watermelon image...", type=["jpg", "jpeg", "png"])
125
 
126
+ # if uploaded_file is not None:
127
+ # try:
128
+ # # Load the image
129
+ # img = image.load_img(uploaded_file, target_size=(224, 224))
130
+ # img_array = image.img_to_array(img)
131
+ # img_array = np.expand_dims(img_array, axis=0)
132
+ # img_array /= 255.0
133
+
134
+ # # Display uploaded image
135
+ # st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
136
+
137
+ # # Predict watermelon name
138
+ # pred_name = model_name.predict(img_array)
139
+ # predicted_name = 'Watermelon'
140
+
141
+ # # Predict watermelon quality
142
+ # pred_quality = model_quality.predict(img_array)
143
+ # predicted_class_quality = np.argmax(pred_quality, axis=1)
144
+
145
+ # # Define labels for watermelon quality
146
+ # label_map_quality = {
147
+ # 0: "Good",
148
+ # 1: "Mild",
149
+ # 2: "Rotten"
150
+ # }
151
+
152
+ # predicted_quality = label_map_quality[predicted_class_quality[0]]
153
+
154
+ # # Display predictions
155
+ # st.write(f"Fruit Type Detection: {predicted_name}")
156
+ # st.write(f"Fruit Quality Classification: {predicted_quality}")
157
+
158
+ # # If the quality is 'Mild' or 'Rotten', pass the image to the mask detection model
159
+ # if predicted_quality in ["Mild", "Rotten"]:
160
+ # st.write("Passing the image to the mask detection model for damage detection...")
161
+
162
+ # # Load the image again for the mask detection (Detectron2 requires the original image)
163
+ # im = cv2.imdecode(np.fromstring(uploaded_file.read(), np.uint8), 1)
164
+
165
+ # # Setup Detectron2 configuration for watermelon
166
+ # cfg = get_cfg()
167
+ # cfg.merge_from_file(detectron_config_path)
168
+ # cfg.MODEL.WEIGHTS = detectron_weights_path
169
+ # cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
170
+ # cfg.MODEL.DEVICE = 'cpu' # Use CPU for inference
171
+
172
+ # predictor = DefaultPredictor(cfg)
173
+ # predictor.model.load_state_dict(torch.load(detectron_weights_path, map_location=torch.device('cpu')))
174
+
175
+ # # Run prediction on the image
176
+ # outputs = predictor(im)
177
+
178
+ # # Visualize the predictions
179
+ # v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8)
180
+ # out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
181
+
182
+ # # Display the output
183
+ # st.image(out.get_image()[:, :, ::-1], caption="Detected Damage", use_column_width=True)
184
+
185
+ # except Exception as e:
186
+ # st.error(f"An error occurred during processing: {str(e)}")