Subiksha0515 commited on
Commit
1fd73d9
·
verified ·
1 Parent(s): 8a88af7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -51
app.py CHANGED
@@ -5,73 +5,87 @@ import os
5
  import random
6
  from tensorflow.keras.preprocessing import image
7
 
8
- # Root dataset folder
 
 
 
 
 
 
 
 
 
 
 
 
9
  DATASET_PATH = "Fruit_Classification"
10
 
11
- # Load class names from dataset folders
12
- class_names = sorted([
13
- folder for folder in os.listdir(DATASET_PATH)
14
- if os.path.isdir(os.path.join(DATASET_PATH, folder))
15
- ])
 
 
16
 
17
  print("Classes:", class_names)
18
 
19
- # Load trained model (your uploaded model)
20
- model = tf.keras.models.load_model("Fruit_Classification_Model.h5")
21
 
22
- print("Model loaded successfully")
23
-
24
-
25
- # Prediction function
26
  def classify_from_text(text_input):
 
 
 
27
 
28
- if text_input is None or text_input.strip() == "":
29
- return None, "Please enter a fruit name"
30
-
31
- text_input = text_input.strip().capitalize()
32
-
33
- # Check valid class
34
- if text_input not in class_names:
35
- return None, f"Invalid fruit name. Valid: {class_names}"
36
-
37
- # Select random image from dataset
38
- folder = os.path.join(DATASET_PATH, text_input)
39
-
40
- images = os.listdir(folder)
41
 
42
- if len(images) == 0:
43
- return None, "No images found in folder"
44
 
45
- img_name = random.choice(images)
46
 
47
- img_path = os.path.join(folder, img_name)
 
48
 
49
- # Load image
50
- img = image.load_img(img_path, target_size=(224,224))
51
 
52
- img_array = image.img_to_array(img)
 
 
 
53
 
54
- img_array = np.expand_dims(img_array, axis=0)
 
55
 
56
- img_array = img_array / 255.0
 
57
 
 
 
 
 
 
58
 
59
- # Predict
60
- prediction = model.predict(img_array, verbose=0)
 
 
 
61
 
62
- predicted_index = np.argmax(prediction)
63
 
64
- predicted_class = class_names[predicted_index]
65
 
66
- confidence = float(np.max(prediction)) * 100
67
-
68
-
69
- result = f"Predicted: {predicted_class}\nConfidence: {confidence:.2f}%"
70
-
71
-
72
- return img, result
73
 
74
 
 
 
 
75
  interface = gr.Interface(
76
  fn=classify_from_text,
77
  inputs=gr.Textbox(
@@ -80,13 +94,12 @@ interface = gr.Interface(
80
  ),
81
  outputs=[
82
  gr.Image(label="Sample Image"),
83
- gr.Textbox(label="Prediction Result") # ✅ UNCOMMENT THIS
84
  ],
85
  title="CNN Fruit Classification System",
86
- description="Enter fruit name → CNN predicts fruit"
87
  )
88
 
89
- # FIX for Hugging Face Spaces reload bug
90
- interface.launch(ssr_mode=False)
91
-
92
-
 
5
  import random
6
  from tensorflow.keras.preprocessing import image
7
 
8
+ # -----------------------------
9
+ # Safe Model Loading
10
+ # -----------------------------
11
+ try:
12
+ model = tf.keras.models.load_model("Fruit_Classification_Model.h5")
13
+ print("Model loaded successfully")
14
+ except Exception as e:
15
+ print("Model loading failed:", e)
16
+ model = None
17
+
18
+ # -----------------------------
19
+ # Safe Dataset Loading
20
+ # -----------------------------
21
  DATASET_PATH = "Fruit_Classification"
22
 
23
+ if os.path.exists(DATASET_PATH):
24
+ class_names = sorted([
25
+ folder for folder in os.listdir(DATASET_PATH)
26
+ if os.path.isdir(os.path.join(DATASET_PATH, folder))
27
+ ])
28
+ else:
29
+ class_names = []
30
 
31
  print("Classes:", class_names)
32
 
 
 
33
 
34
+ # -----------------------------
35
+ # Prediction Function
36
+ # -----------------------------
 
37
  def classify_from_text(text_input):
38
+ try:
39
+ if model is None:
40
+ return None, "Model not loaded properly."
41
 
42
+ if not class_names:
43
+ return None, "Dataset folder not found."
 
 
 
 
 
 
 
 
 
 
 
44
 
45
+ if text_input is None or text_input.strip() == "":
46
+ return None, "Please enter a fruit name."
47
 
48
+ text_input = text_input.strip().capitalize()
49
 
50
+ if text_input not in class_names:
51
+ return None, f"Invalid fruit name.\nValid: {class_names}"
52
 
53
+ folder = os.path.join(DATASET_PATH, text_input)
 
54
 
55
+ images = [
56
+ img for img in os.listdir(folder)
57
+ if img.lower().endswith((".jpg", ".jpeg", ".png"))
58
+ ]
59
 
60
+ if len(images) == 0:
61
+ return None, "No images found in folder."
62
 
63
+ img_name = random.choice(images)
64
+ img_path = os.path.join(folder, img_name)
65
 
66
+ # Load and preprocess image
67
+ img = image.load_img(img_path, target_size=(224, 224))
68
+ img_array = image.img_to_array(img)
69
+ img_array = np.expand_dims(img_array, axis=0)
70
+ img_array = img_array / 255.0
71
 
72
+ # Predict
73
+ prediction = model.predict(img_array, verbose=0)
74
+ predicted_index = np.argmax(prediction)
75
+ predicted_class = class_names[predicted_index]
76
+ confidence = float(np.max(prediction)) * 100
77
 
78
+ result = f"Predicted: {predicted_class}\nConfidence: {confidence:.2f}%"
79
 
80
+ return img, result
81
 
82
+ except Exception as e:
83
+ return None, f"Error occurred: {str(e)}"
 
 
 
 
 
84
 
85
 
86
+ # -----------------------------
87
+ # Gradio Interface
88
+ # -----------------------------
89
  interface = gr.Interface(
90
  fn=classify_from_text,
91
  inputs=gr.Textbox(
 
94
  ),
95
  outputs=[
96
  gr.Image(label="Sample Image"),
97
+ gr.Textbox(label="Prediction Result")
98
  ],
99
  title="CNN Fruit Classification System",
100
+ description="Enter fruit name → CNN selects sample image → CNN predicts fruit"
101
  )
102
 
103
+ # Launch normally (DO NOT use ssr_mode=False)
104
+ if __name__ == "__main__":
105
+ interface.launch()