BunkerMinecraft commited on
Commit
8362209
·
verified ·
1 Parent(s): f2515f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -47
app.py CHANGED
@@ -1,61 +1,118 @@
1
- import tensorflow as tf
2
- from tensorflow.keras import layers, models, regularizers
3
  import json
4
- from PIL import Image
5
  import numpy as np
6
- import os
 
 
 
7
  import gradio as gr
8
 
9
- # ---- Load config if present ----
10
- cfg = None
 
 
 
11
  if os.path.exists("config.json"):
12
  with open("config.json") as f:
13
  cfg = json.load(f)
14
 
15
- # ---- Class labels ----
16
- class_names = ['battery', 'glass', 'metal', 'organic', 'paper', 'plastic']
 
 
 
17
 
18
- # ---- Build model architecture ----
19
- base_model = tf.keras.applications.EfficientNetB7(
20
- weights='imagenet',
21
- include_top=False,
22
- input_shape=(224, 224, 3)
23
- )
24
- base_model.trainable = False
25
-
26
- model = models.Sequential([
27
- base_model,
28
- layers.GlobalAveragePooling2D(),
29
- layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(0.001)),
30
- layers.Dropout(0.3),
31
- layers.Dense(128, activation='relu', kernel_regularizer=regularizers.l2(0.001)),
32
- layers.Dropout(0.3),
33
- layers.Dense(6, activation='softmax')
34
- ])
35
-
36
- # ---- Load trained weights ----
37
- if os.path.exists("model_weights.h5"):
38
- model.load_weights("model_weights.h5")
39
- print("Weights loaded successfully.")
40
- else:
41
- print("model_weights.h5 not found! Current directory:", os.listdir())
42
-
43
- # ---- Preprocess image ----
44
- def preprocess(image: Image.Image):
45
- image = image.resize((224, 224))
46
- image = np.array(image) / 255.0
47
- image = np.expand_dims(image, axis=0)
48
- return image
49
-
50
- # ---- Prediction function ----
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  def predict(image: Image.Image):
 
 
 
52
  x = preprocess(image)
53
- preds = model.predict(x)
54
- class_idx = int(np.argmax(preds, axis=1)[0])
55
- confidence = float(np.max(preds))
56
  return class_names[class_idx], confidence
57
 
58
- # ---- Gradio interface ----
 
 
 
59
  interface = gr.Interface(
60
  fn=predict,
61
  inputs=gr.Image(type="pil", label="Upload an image"),
@@ -64,9 +121,9 @@ interface = gr.Interface(
64
  gr.Number(label="Confidence")
65
  ],
66
  title="NeuRecAI - Material Classifier",
67
- description="Upload an image to classify it as battery, glass, metal, organic, paper, or plastic."
 
68
  )
69
 
70
- # ---- Launch ----
71
  if __name__ == "__main__":
72
  interface.launch()
 
1
+ import os
 
2
  import json
 
3
  import numpy as np
4
+ from PIL import Image
5
+ import tensorflow as tf
6
+ from tensorflow.keras import layers, models, regularizers
7
+ from tensorflow.keras.applications.efficientnet import preprocess_input
8
  import gradio as gr
9
 
10
+
11
+ # -----------------------
12
+ # Config and class labels
13
+ # -----------------------
14
+ cfg = {}
15
  if os.path.exists("config.json"):
16
  with open("config.json") as f:
17
  cfg = json.load(f)
18
 
19
+ # Default labels; override via config.json if provided
20
+ default_class_names = ['battery', 'glass', 'metal', 'organic', 'paper', 'plastic']
21
+ class_names = cfg.get("class_names", default_class_names)
22
+ num_classes = int(cfg.get("num_classes", len(class_names)))
23
+ assert num_classes == len(class_names), "num_classes must equal len(class_names)"
24
 
25
+
26
+ # -----------------------
27
+ # Model construction
28
+ # -----------------------
29
+ def build_model(num_classes: int) -> tf.keras.Model:
30
+ """
31
+ Rebuild the exact training head to load .h5 weights reliably.
32
+ Uses EfficientNetB7 backbone with a small dense head.
33
+ """
34
+ base_model = tf.keras.applications.EfficientNetB7(
35
+ weights="imagenet", # keep as used during training
36
+ include_top=False,
37
+ input_shape=(224, 224, 3)
38
+ )
39
+ base_model.trainable = False
40
+
41
+ model = models.Sequential([
42
+ base_model,
43
+ layers.GlobalAveragePooling2D(),
44
+ layers.Dense(256, activation="relu",
45
+ kernel_regularizer=regularizers.l2(0.001)),
46
+ layers.Dropout(0.3),
47
+ layers.Dense(128, activation="relu",
48
+ kernel_regularizer=regularizers.l2(0.001)),
49
+ layers.Dropout(0.3),
50
+ layers.Dense(num_classes, activation="softmax")
51
+ ])
52
+ return model
53
+
54
+
55
+ # -----------------------
56
+ # Load model or weights
57
+ # -----------------------
58
+ model = None
59
+ _loaded_full = False
60
+
61
+ # Prefer a full saved model if available
62
+ for fname in ("model.keras", "model.h5"):
63
+ if os.path.exists(fname):
64
+ model = tf.keras.models.load_model(fname, compile=False)
65
+ _loaded_full = True
66
+ print(f"Loaded full model from {fname}")
67
+ break
68
+
69
+ if model is None:
70
+ # Fallback: rebuild and load weights
71
+ model = build_model(num_classes)
72
+ weights_path = "model_weights.h5" if os.path.exists("model_weights.h5") else "model.weights.h5"
73
+ if os.path.exists(weights_path):
74
+ model.load_weights(weights_path)
75
+ print(f"Weights loaded from {weights_path}.")
76
+ else:
77
+ print("No model file found: expected model.keras/model.h5 or model_weights.h5/model.weights.h5.")
78
+ print("Current directory:", os.listdir())
79
+
80
+
81
+ # -----------------------
82
+ # Preprocessing
83
+ # -----------------------
84
+ def _to_rgb(img: Image.Image) -> Image.Image:
85
+ """Force 3-channel RGB to avoid grayscale/RGBA issues."""
86
+ return img.convert("RGB")
87
+
88
+ def preprocess(image: Image.Image) -> np.ndarray:
89
+ """
90
+ Resize to 224, EfficientNet preprocess, add batch dimension.
91
+ """
92
+ image = _to_rgb(image).resize((224, 224), Image.BILINEAR)
93
+ x = np.asarray(image, dtype=np.float32)
94
+ x = preprocess_input(x) # correct scaling for EfficientNet
95
+ x = np.expand_dims(x, axis=0) # (1, 224, 224, 3)
96
+ return x
97
+
98
+
99
+ # -----------------------
100
+ # Inference
101
+ # -----------------------
102
  def predict(image: Image.Image):
103
+ """
104
+ Returns (label, confidence) for Gradio.
105
+ """
106
  x = preprocess(image)
107
+ preds = model.predict(x, verbose=0)[0] # shape: (num_classes,)
108
+ class_idx = int(np.argmax(preds))
109
+ confidence = float(preds[class_idx])
110
  return class_names[class_idx], confidence
111
 
112
+
113
+ # -----------------------
114
+ # Gradio interface
115
+ # -----------------------
116
  interface = gr.Interface(
117
  fn=predict,
118
  inputs=gr.Image(type="pil", label="Upload an image"),
 
121
  gr.Number(label="Confidence")
122
  ],
123
  title="NeuRecAI - Material Classifier",
124
+ description=("Upload an image to classify it as battery, glass, metal, organic, "
125
+ "paper, or plastic.")
126
  )
127
 
 
128
  if __name__ == "__main__":
129
  interface.launch()