ivanmichael commited on
Commit
a37a6c6
·
verified ·
1 Parent(s): 4eb7038

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -81
app.py CHANGED
@@ -1,97 +1,71 @@
1
  import gradio as gr
2
  import tensorflow as tf
3
- from PIL import Image
4
  import numpy as np
5
- import os
6
- import logging
7
- import traceback
8
-
9
- # Set up logging
10
- logging.basicConfig(level=logging.INFO)
11
- logger = logging.getLogger(__name__)
12
-
13
- # Debug file system
14
- logger.info("Current directory contents: %s", os.listdir())
15
- logger.info("Model exists: %s", os.path.exists("model.keras"))
16
-
17
- class ImageClassifier:
18
- def __init__(self, model_path):
19
- try:
20
- logger.info("Loading model...")
21
- self.model = tf.keras.models.load_model(model_path)
22
- logger.info("Model loaded successfully")
23
- self.model.summary(print_fn=logger.info)
24
- except Exception as e:
25
- logger.error("Model loading failed", exc_info=True)
26
- raise
27
-
28
- # Update these based on your model
29
- self.input_size = (224, 224)
30
- self.class_names = ['class1', 'class2', 'class3']
31
 
32
- def preprocess_image(self, image):
33
- try:
34
- logger.info("Preprocessing image")
35
- image = image.resize(self.input_size)
36
- image_array = np.array(image)
37
- image_array = image_array / 255.0
38
- image_array = np.expand_dims(image_array, axis=0)
39
- logger.info("Image preprocessed - shape: %s", image_array.shape)
40
- return image_array
41
- except Exception as e:
42
- logger.error("Preprocessing failed", exc_info=True)
43
- raise
44
 
45
- def predict(self, image):
46
- try:
47
- processed_image = self.preprocess_image(image)
48
- logger.info("Making prediction...")
49
- predictions = self.model.predict(processed_image)
50
- logger.info("Raw predictions: %s", predictions)
51
- predicted_class = np.argmax(predictions[0])
52
- confidence = np.max(predictions[0])
53
- return {
54
- 'class': self.class_names[predicted_class],
55
- 'confidence': float(confidence),
56
- 'all_predictions': predictions.tolist()
57
- }
58
- except Exception as e:
59
- logger.error("Prediction failed", exc_info=True)
60
- raise
61
 
62
- try:
63
- classifier = ImageClassifier("model.keras")
64
- except Exception as e:
65
- logger.error("Failed to initialize classifier", exc_info=True)
66
- raise
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  def classify_image(image):
 
 
 
69
  try:
70
- logger.info("Received image type: %s", type(image))
71
- if isinstance(image, np.ndarray):
72
- logger.info("Image shape: %s", image.shape)
73
- pil_image = Image.fromarray(image)
74
- else:
75
- pil_image = image
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- logger.info("Converted to PIL format")
78
- result = classifier.predict(pil_image)
79
- logger.info("Prediction result: %s", result)
80
- return result
81
  except Exception as e:
82
- logger.error("Classification error", exc_info=True)
83
- return f"Error: {str(e)}"
84
 
 
85
  interface = gr.Interface(
86
  fn=classify_image,
87
- inputs=gr.Image(label="Upload an image"),
88
- outputs=[
89
- gr.Label(label="Predicted Class"),
90
- gr.Number(label="Confidence Score"),
91
- gr.JSON(label="All Predictions")
92
- ],
93
- title="Image Classification",
94
- allow_flagging="never"
95
  )
96
 
97
- interface.launch(debug=True, server_name="0.0.0.0", server_port=7860)
 
 
1
  import gradio as gr
2
  import tensorflow as tf
 
3
  import numpy as np
4
+ from PIL import Image
5
+ import json
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # Load the model (replace 'your_model.keras' with your actual filename)
8
+ model = tf.keras.models.load_model('model.keras')
 
 
 
 
 
 
 
 
 
 
9
 
10
+ # Load class labels
11
+ with open("class_labels.json", "r") as f:
12
+ class_labels = json.load(f)
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ def preprocess_image(image):
15
+ """
16
+ Preprocess the uploaded image to match model requirements
17
+ """
18
+ # Convert PIL image to numpy array
19
+ img_array = np.array(image)
20
+
21
+ # Resize image to match model input size (256x256 for your model)
22
+ img_resized = tf.image.resize(img_array, [256, 256])
23
+
24
+ # Normalize pixel values (adjust based on your model's training)
25
+ img_normalized = tf.cast(img_resized, tf.float32) / 255.0
26
+
27
+ # Add batch dimension
28
+ img_batch = tf.expand_dims(img_normalized, 0)
29
+
30
+ return img_batch
31
 
32
  def classify_image(image):
33
+ """
34
+ Classify the uploaded image and return predictions
35
+ """
36
  try:
37
+ # Preprocess the image
38
+ processed_image = preprocess_image(image)
39
+
40
+ # Make prediction
41
+ predictions = model.predict(processed_image)
42
+
43
+ # Get the predicted class probabilities
44
+ probabilities = tf.nn.softmax(predictions[0]).numpy()
45
+
46
+ # Create a dictionary of class labels and their probabilities
47
+ results = {}
48
+ for i, prob in enumerate(probabilities):
49
+ if i < len(class_labels):
50
+ results[class_labels[i]] = float(prob)
51
+
52
+ # Sort by probability (highest first)
53
+ sorted_results = dict(sorted(results.items(), key=lambda x: x[1], reverse=True))
54
+
55
+ return sorted_results
56
 
 
 
 
 
57
  except Exception as e:
58
+ return {"Error": f"Classification failed: {str(e)}"}
 
59
 
60
+ # Create Gradio interface
61
  interface = gr.Interface(
62
  fn=classify_image,
63
+ inputs=gr.Image(type="pil", label="Upload an image"),
64
+ outputs=gr.Label(num_top_classes=5, label="Predictions"),
65
+ title="Image Classification Model",
66
+ description="Upload an image to classify it using the trained model",
67
+ examples=["example1.jpg", "example2.jpg"] # Add example images if available
 
 
 
68
  )
69
 
70
+ if __name__ == "__main__":
71
+ interface.launch()