File size: 22,068 Bytes
df1d7ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e18493d
 
 
 
 
8773d3c
e18493d
 
 
 
 
 
8773d3c
e18493d
8773d3c
e18493d
 
 
 
 
8773d3c
e18493d
 
 
8773d3c
e18493d
 
8773d3c
e18493d
 
8773d3c
e18493d
 
 
 
8773d3c
e18493d
 
 
 
 
8773d3c
e18493d
 
 
df1d7ff
e18493d
 
df1d7ff
e18493d
 
 
df1d7ff
 
 
76c62bb
9f80c53
 
 
 
76c62bb
 
 
e18493d
 
 
 
 
 
 
 
 
 
 
 
9f80c53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df1d7ff
9f80c53
 
df1d7ff
9f80c53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e18493d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2205388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd891ff
 
 
59d62bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3734d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e18493d
 
 
2205388
83eb0c6
e18493d
 
 
 
 
 
 
 
 
 
 
 
 
6472b08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e18493d
bd891ff
1523d77
3734d84
 
 
6472b08
3734d84
 
 
 
 
 
 
 
 
 
 
 
 
 
1523d77
 
 
 
 
 
 
3734d84
 
1523d77
3734d84
 
6472b08
 
 
 
3734d84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1523d77
3734d84
1523d77
 
 
3734d84
1523d77
3734d84
1523d77
 
 
3734d84
1523d77
 
83eb0c6
1523d77
 
83eb0c6
1523d77
 
6472b08
 
 
 
 
 
 
 
1523d77
 
83eb0c6
1523d77
6472b08
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
# import streamlit as st

# # Set title of the app
# st.title("Simple Streamlit App")

# # Add text input
# user_input = st.text_input("Enter your name:")

# # Display the input value
# if user_input:
#     st.write(f"Hello, {user_input}!")







# import streamlit as st
# from tensorflow.keras.models import load_model
# from tensorflow.keras.preprocessing import image
# import numpy as np
# from PIL import Image

# # Load the pre-trained models
# @st.cache_resource
# def load_models():
#     model1 = load_model('name_model_inception.h5')  # Update with your Hugging Face model path
#     model2 = load_model('type_model_inception.h5')  # Update with your Hugging Face model path
#     return model1, model2

# model1, model2 = load_models()

# # Label mappings
# label_map1 = {
#     0: "Banana", 1: "Cucumber", 2: "Grape", 3: "Kaki", 4: "Papaya",
#     5: "Peach", 6: "Pear", 7: "Pepper", 8: "Strawberry", 9: "Watermelon", 10: "Tomato"
# }

# label_map2 = {
#     0: "Good", 1: "Mild", 2: "Rotten"
# }

# # Streamlit app layout
# st.title("Fruit Classifier")

# # Upload image
# uploaded_file = st.file_uploader("Choose an image of a fruit", type=["jpg", "jpeg", "png"])

# if uploaded_file is not None:
#     # Display the uploaded image
#     img = Image.open(uploaded_file)
#     st.image(img, caption="Uploaded Image", use_column_width=True)
    
#     # Preprocess the image
#     img = img.resize((224, 224))  # Resize image to match the model input
#     img_array = image.img_to_array(img)
#     img_array = np.expand_dims(img_array, axis=0)
#     img_array = img_array / 255.0  # Normalize the image

#     # Make predictions
#     pred1 = model1.predict(img_array)
#     pred2 = model2.predict(img_array)

#     predicted_class1 = np.argmax(pred1, axis=1)
#     predicted_class2 = np.argmax(pred2, axis=1)

#     # Display results
#     st.write(f"**Type Detection**: {label_map1[predicted_class1[0]]}")
#     st.write(f"**Condition Detection**: {label_map2[predicted_class2[0]]}")




# !git clone 'https://github.com/facebookresearch/detectron2'
# dist = distutils.core.run_setup("./detectron2/setup.py")
# !python -m pip install {' '.join([f"'{x}'" for x in dist.install_requires])}
# sys.path.insert(0, os.path.abspath('./detectron2'))















# import streamlit as st
# import numpy as np
# import cv2
# import warnings

# # Suppress warnings
# warnings.filterwarnings("ignore", category=FutureWarning)
# warnings.filterwarnings("ignore", category=UserWarning)

# # Try importing TensorFlow
# try:
#     from tensorflow.keras.models import load_model
#     from tensorflow.keras.preprocessing import image
# except ImportError:
#     st.error("Failed to import TensorFlow. Please make sure it's installed correctly.")

# # Try importing PyTorch and Detectron2
# try:
#     import torch
#     from detectron2.engine import DefaultPredictor
#     from detectron2.config import get_cfg
#     from detectron2.utils.visualizer import Visualizer
#     from detectron2.data import MetadataCatalog
# except ImportError:
#     st.error("Failed to import PyTorch or Detectron2. Please make sure they're installed correctly.")

# # Load the trained models
# try:
#     model_path_name = 'name_model_inception.h5'
#     model_path_quality = 'type_model_inception.h5'
#     detectron_config_path = 'watermelon.yaml'
#     detectron_weights_path = 'Watermelon_model.pth'

#     model_name = load_model(model_path_name)
#     model_quality = load_model(model_path_quality)
# except Exception as e:
#     st.error(f"Failed to load models: {str(e)}")

# # Streamlit app title
# st.title("Watermelon Quality and Damage Detection")

# # Upload image
# uploaded_file = st.file_uploader("Choose a watermelon image...", type=["jpg", "jpeg", "png"])

# if uploaded_file is not None:
#     try:
#         # Load the image
#         img = image.load_img(uploaded_file, target_size=(224, 224))
#         img_array = image.img_to_array(img)
#         img_array = np.expand_dims(img_array, axis=0)
#         img_array /= 255.0

#         # Display uploaded image
#         st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)

#         # Predict watermelon name
#         pred_name = model_name.predict(img_array)
#         predicted_name = 'Watermelon'

#         # Predict watermelon quality
#         pred_quality = model_quality.predict(img_array)
#         predicted_class_quality = np.argmax(pred_quality, axis=1)

#         # Define labels for watermelon quality
#         label_map_quality = {
#             0: "Good",
#             1: "Mild",
#             2: "Rotten"
#         }

#         predicted_quality = label_map_quality[predicted_class_quality[0]]

#         # Display predictions
#         st.write(f"Fruit Type Detection: {predicted_name}")
#         st.write(f"Fruit Quality Classification: {predicted_quality}")

#         # If the quality is 'Mild' or 'Rotten', pass the image to the mask detection model
#         if predicted_quality in ["Mild", "Rotten"]:
#             st.write("Passing the image to the mask detection model for damage detection...")

#             # Load the image again for the mask detection (Detectron2 requires the original image)
#             im = cv2.imdecode(np.fromstring(uploaded_file.read(), np.uint8), 1)

#             # Setup Detectron2 configuration for watermelon
#             cfg = get_cfg()
#             cfg.merge_from_file(detectron_config_path)
#             cfg.MODEL.WEIGHTS = detectron_weights_path
#             cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
#             cfg.MODEL.DEVICE = 'cpu'  # Use CPU for inference

#             predictor = DefaultPredictor(cfg)
#             predictor.model.load_state_dict(torch.load(detectron_weights_path, map_location=torch.device('cpu')))

#             # Run prediction on the image
#             outputs = predictor(im)

#             # Visualize the predictions
#             v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8)
#             out = v.draw_instance_predictions(outputs["instances"].to("cpu"))

#             # Display the output
#             st.image(out.get_image()[:, :, ::-1], caption="Detected Damage", use_column_width=True)

#     except Exception as e:
#         st.error(f"An error occurred during processing: {str(e)}")
















# import streamlit as st
# import numpy as np
# import cv2
# import warnings
# import os

# # Suppress warnings
# warnings.filterwarnings("ignore", category=FutureWarning)
# warnings.filterwarnings("ignore", category=UserWarning)

# # Try importing TensorFlow
# try:
#     from tensorflow.keras.models import load_model
#     from tensorflow.keras.preprocessing import image
# except ImportError:
#     st.error("Failed to import TensorFlow. Please make sure it's installed correctly.")

# # Try importing PyTorch and Detectron2
# try:
#     import torch
#     import detectron2
# except ImportError:
#     with st.spinner("Installing PyTorch and Detectron2..."):
#         os.system("pip install torch torchvision")
#         os.system("pip install 'git+https://github.com/facebookresearch/detectron2.git'")

#     import torch
#     import detectron2

# from detectron2.engine import DefaultPredictor
# from detectron2.config import get_cfg
# from detectron2.utils.visualizer import Visualizer
# from detectron2.data import MetadataCatalog

# # Load the trained models
# @st.cache_resource
# def load_models():
#     try:
#         model_path_name = 'name_model_inception.h5'
#         model_path_quality = 'type_model_inception.h5'
#         model_name = load_model(model_path_name)
#         model_quality = load_model(model_path_quality)
#         return model_name, model_quality
#     except Exception as e:
#         st.error(f"Failed to load models: {str(e)}")
#         return None, None

# model_name, model_quality = load_models()

# # Streamlit app title
# st.title("Watermelon Quality and Damage Detection")

# # Upload image
# uploaded_file = st.file_uploader("Choose a watermelon image...", type=["jpg", "jpeg", "png"])

# if uploaded_file is not None:
#     try:
#         # Load the image
#         img = image.load_img(uploaded_file, target_size=(224, 224))
#         img_array = image.img_to_array(img)
#         img_array = np.expand_dims(img_array, axis=0)
#         img_array /= 255.0

#         # Display uploaded image
#         st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)

#         # Predict watermelon name
#         pred_name = model_name.predict(img_array)
#         predicted_name = 'Watermelon'

#         # Predict watermelon quality
#         pred_quality = model_quality.predict(img_array)
#         predicted_class_quality = np.argmax(pred_quality, axis=1)

#         # Define labels for watermelon quality
#         label_map_quality = {
#             0: "Good",
#             1: "Mild",
#             2: "Rotten"
#         }

#         predicted_quality = label_map_quality[predicted_class_quality[0]]

#         # Display predictions
#         st.write(f"Fruit Type Detection: {predicted_name}")
#         st.write(f"Fruit Quality Classification: {predicted_quality}")

#         # If the quality is 'Mild' or 'Rotten', pass the image to the mask detection model
#         if predicted_quality in ["Mild", "Rotten"]:
#             st.write("Passing the image to the mask detection model for damage detection...")

#             # Load the image again for the mask detection (Detectron2 requires the original image)
#             im = cv2.imdecode(np.fromstring(uploaded_file.read(), np.uint8), 1)

#             # Setup Detectron2 configuration for watermelon
#             @st.cache_resource
#             def load_detectron_model():
#                 cfg = get_cfg()
#                 cfg.merge_from_file("watermelon.yaml")
#                 cfg.MODEL.WEIGHTS = "Watermelon_model.pth"
#                 cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
#                 cfg.MODEL.DEVICE = 'cpu'  # Use CPU for inference
#                 predictor = DefaultPredictor(cfg)
#                 return predictor

#             predictor = load_detectron_model()

#             # Run prediction on the image
#             outputs = predictor(im)

#             # Visualize the predictions
#             v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8)
#             out = v.draw_instance_predictions(outputs["instances"].to("cpu"))

#             # Display the output
#             st.image(out.get_image()[:, :, ::-1], caption="Detected Damage", use_column_width=True)

#     except Exception as e:
#         st.error(f"An error occurred during processing: {str(e)}")







# ///////////////////////////////////Working


import streamlit as st
import numpy as np
import cv2
import warnings
import os

# Suppress warnings
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)

# Try importing TensorFlow
try:
    from tensorflow.keras.models import load_model
    from tensorflow.keras.preprocessing import image
except ImportError:
    st.error("Failed to import TensorFlow. Please make sure it's installed correctly.")

# Try importing PyTorch and Detectron2
try:
    import torch
    import detectron2
except ImportError:
    with st.spinner("Installing PyTorch and Detectron2..."):
        os.system("pip install torch torchvision")
        os.system("pip install 'git+https://github.com/facebookresearch/detectron2.git'")

    import torch
    import detectron2

from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog

# # Load the trained models
# @st.cache_resource
# def load_models():
#     try:
#         model_path_name = 'name_model_inception.h5'
#         model_path_quality = 'type_model_inception.h5'
#         model_name = load_model(model_path_name)
#         model_quality = load_model(model_path_quality)
#         return model_name, model_quality
#     except Exception as e:
#         st.error(f"Failed to load models: {str(e)}")
#         return None, None

# model_name, model_quality = load_models()

# # Setup Detectron2 configuration for watermelon
# @st.cache_resource
# def load_detectron_model():
#     cfg = get_cfg()
#     cfg.merge_from_file("watermelon.yaml")
#     cfg.MODEL.WEIGHTS = "Watermelon_model.pth"
#     cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
#     cfg.MODEL.DEVICE = 'cpu'  # Use CPU for inference
#     predictor = DefaultPredictor(cfg)
#     return predictor, cfg

# predictor, cfg = load_detectron_model()

# # Streamlit app title
# st.title("Watermelon Quality and Damage Detection")

# # Upload image
# uploaded_file = st.file_uploader("Choose a watermelon image...", type=["jpg", "jpeg", "png"])

# if uploaded_file is not None:
#     try:
#         # Load the image
#         img = image.load_img(uploaded_file, target_size=(224, 224))
#         img_array = image.img_to_array(img)
#         img_array = np.expand_dims(img_array, axis=0)
#         img_array /= 255.0

#         # Display uploaded image
#         st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)

#         # Predict watermelon name
#         pred_name = model_name.predict(img_array)
#         predicted_name = 'Watermelon'

#         # Predict watermelon quality
#         pred_quality = model_quality.predict(img_array)
#         predicted_class_quality = np.argmax(pred_quality, axis=1)

#         # Define labels for watermelon quality
#         label_map_quality = {
#             0: "Good",
#             1: "Mild",
#             2: "Rotten"
#         }

#         predicted_quality = label_map_quality[predicted_class_quality[0]]

#         # Display predictions
#         st.write(f"Fruit Type Detection: {predicted_name}")
#         st.write(f"Fruit Quality Classification: {predicted_quality}")

#         # If the quality is 'Mild' or 'Rotten', pass the image to the mask detection model
#         if predicted_quality in ["Mild", "Rotten"]:
#             st.write("Passing the image to the mask detection model for damage detection...")

#             # Load the image again for the mask detection (Detectron2 requires the original image)
#             im = cv2.imdecode(np.fromstring(uploaded_file.read(), np.uint8), 1)

#             # Run prediction on the image
#             outputs = predictor(im)

#             # Visualize the predictions
#             v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8)
#             out = v.draw_instance_predictions(outputs["instances"].to("cpu"))

#             # Display the output
#             st.image(out.get_image()[:, :, ::-1], caption="Detected Damage", use_column_width=True)

#     except Exception as e:
#         st.error(f"An error occurred during processing: {str(e)}")























# import streamlit as st
# import numpy as np
# import cv2
# import torch
# from PIL import Image
# from tensorflow.keras.models import load_model
# from tensorflow.keras.preprocessing import image
# from detectron2.engine import DefaultPredictor
# from detectron2.config import get_cfg
# from detectron2.utils.visualizer import Visualizer
# from detectron2.data import MetadataCatalog

# # Suppress warnings
# import warnings
# import tensorflow as tf
# warnings.filterwarnings("ignore")
# tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

# @st.cache_resource
# def load_models():
#     model_name = load_model('name_model_inception.h5')
#     model_quality = load_model('type_model_inception.h5')
#     return model_name, model_quality

# model_name, model_quality = load_models()

# # Detectron2 setup
# @st.cache_resource
# def load_detectron_model(fruit_name):
#     cfg = get_cfg()
#     cfg.merge_from_file(f"{fruit_name.lower()}.yaml")
#     cfg.MODEL.WEIGHTS = f"{fruit_name.lower()}_model.pth"
#     cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
#     cfg.MODEL.DEVICE = 'cpu'
#     predictor = DefaultPredictor(cfg)
#     return predictor, cfg

# # Labels
# label_map_name = {
#     0: "Banana", 1: "Cucumber", 2: "Grape", 3: "Kaki", 4: "Papaya",
#     5: "Peach", 6: "Pear", 7: "Pepper", 8: "Strawberry", 9: "Watermelon",
#     10: "Tomato"
# }
# label_map_quality = {0: "Good", 1: "Mild", 2: "Rotten"}

# def predict_fruit(img):
#     # Preprocess image
#     img = Image.fromarray(img.astype('uint8'), 'RGB')
#     img = img.resize((224, 224))
#     x = image.img_to_array(img)
#     x = np.expand_dims(x, axis=0)
#     x = x / 255.0

#     # Predict
#     pred_name = model_name.predict(x)
#     pred_quality = model_quality.predict(x)

#     predicted_name = label_map_name[np.argmax(pred_name, axis=1)[0]]
#     predicted_quality = label_map_quality[np.argmax(pred_quality, axis=1)[0]]

#     return predicted_name, predicted_quality, img

# def main():
#     st.title("Fruit Quality and Damage Detection")
#     st.write("Upload an image of a fruit to detect its type, quality, and potential damage.")

#     uploaded_file = st.file_uploader("Choose a fruit image...", type=["jpg", "jpeg", "png"])

#     if uploaded_file is not None:
#         image = Image.open(uploaded_file)
#         st.image(image, caption="Uploaded Image", use_column_width=True)

#         if st.button("Analyze"):
#             predicted_name, predicted_quality, img = predict_fruit(np.array(image))

#             st.write(f"Fruit Type: {predicted_name}")
#             st.write(f"Fruit Quality: {predicted_quality}")

#             if predicted_name.lower() in ["kaki", "tomato", "strawberry", "pepper", "pear", "peach", "papaya", "watermelon", "grape", "banana", "cucumber"] and predicted_quality in ["Mild", "Rotten"]:
#                 st.write("Detecting damage...")
#                 predictor, cfg = load_detectron_model(predicted_name)
#                 outputs = predictor(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))
#                 v = Visualizer(np.array(img), MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8)
#                 out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
#                 st.image(out.get_image(), caption="Damage Detection Result", use_column_width=True)
#             else:
#                 st.write("No damage detection performed for this fruit or quality level.")

# if __name__ == "__main__":
#     main()











import streamlit as st
import numpy as np
import cv2
import torch
import os
from PIL import Image
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog

# Suppress warnings
import warnings
import tensorflow as tf
warnings.filterwarnings("ignore")
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

@st.cache_resource
def load_models():
    model_name = load_model('name_model_inception.h5')
    model_quality = load_model('type_model_inception.h5')
    return model_name, model_quality

model_name, model_quality = load_models()

# Detectron2 setup
@st.cache_resource
def load_detectron_model(fruit_name):
    cfg = get_cfg()
    config_path = os.path.join('utils', f"{fruit_name.lower()}_config.yaml")
    cfg.merge_from_file(config_path)
    model_path = os.path.join('models', f"{fruit_name.lower()}_model.pth")
    cfg.MODEL.WEIGHTS = model_path
    cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
    cfg.MODEL.DEVICE = 'cpu'
    predictor = DefaultPredictor(cfg)
    return predictor, cfg

# Labels
label_map_name = {
    0: "Banana", 1: "Cucumber", 2: "Grape", 3: "Kaki", 4: "Papaya",
    5: "Peach", 6: "Pear", 7: "Pepper", 8: "Strawberry", 9: "Watermelon",
    10: "Tomato"
}
label_map_quality = {0: "Good", 1: "Mild", 2: "Rotten"}

def predict_fruit(img):
    # Preprocess image
    img = Image.fromarray(img.astype('uint8'), 'RGB')
    img = img.resize((224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = x / 255.0

    # Predict
    pred_name = model_name.predict(x)
    pred_quality = model_quality.predict(x)

    predicted_name = label_map_name[np.argmax(pred_name, axis=1)[0]]
    predicted_quality = label_map_quality[np.argmax(pred_quality, axis=1)[0]]

    return predicted_name, predicted_quality, img

def main():
    st.title("Fruit Quality and Damage Detection")
    st.write("Upload an image of a fruit to detect its type, quality, and potential damage.")

    uploaded_file = st.file_uploader("Choose a fruit image...", type=["jpg", "jpeg", "png"])

    if uploaded_file is not None:
        image = Image.open(uploaded_file)
        st.image(image, caption="Uploaded Image", use_column_width=True)

        if st.button("Analyze"):
            predicted_name, predicted_quality, img = predict_fruit(np.array(image))

            st.write(f"Fruit Type: {predicted_name}")
            st.write(f"Fruit Quality: {predicted_quality}")

            if predicted_name.lower() in ["kaki", "tomato", "strawberry", "pepper", "pear", "peach", "papaya", "watermelon", "grape", "banana", "cucumber"] and predicted_quality in ["Mild", "Rotten"]:
                st.write("Detecting damage...")
                try:
                    predictor, cfg = load_detectron_model(predicted_name)
                    outputs = predictor(cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR))
                    v = Visualizer(np.array(img), MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=0.8)
                    out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
                    st.image(out.get_image(), caption="Damage Detection Result", use_column_width=True)
                except Exception as e:
                    st.error(f"Error in damage detection: {str(e)}")
            else:
                st.write("No damage detection performed for this fruit or quality level.")

if __name__ == "__main__":
    main()