yolac commited on
Commit
d1439d9
·
verified ·
1 Parent(s): 58505dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -52
app.py CHANGED
@@ -1,62 +1,72 @@
1
  import gradio as gr
2
  import tensorflow as tf
3
- from PIL import Image
 
4
  import numpy as np
5
- import logging
6
-
7
- # Set up logging for debugging
8
- logging.basicConfig(level=logging.DEBUG)
9
 
10
- # Load the .keras model
11
  MODEL_PATH = "https://huggingface.co/yolac/BacterialMorphologyClassification/resolve/main/model.keras"
12
- logging.debug("Starting model loading...")
13
- try:
14
- model = tf.keras.models.load_model(MODEL_PATH)
15
- logging.debug("Model loaded successfully.")
16
- except Exception as e:
17
- logging.error(f"Error loading the model: {str(e)}")
18
-
19
- # Define image preprocessing transformations
 
 
 
 
 
 
 
 
 
 
 
 
20
  def preprocess_image(image):
21
- logging.debug("Preprocessing image...")
22
- image = image.resize((224, 224)) # Resize to match model input size
23
- image_array = np.array(image) / 255.0 # Normalize pixel values
24
- if len(image_array.shape) == 2: # If grayscale, convert to RGB
25
- image_array = np.stack([image_array] * 3, axis=-1)
26
- image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
27
- return image_array
28
-
29
- # Define the prediction function
30
- def predict(image):
31
- try:
32
- # Preprocess the image
33
- image_array = preprocess_image(image)
34
- logging.debug("Image preprocessing completed.")
35
-
36
- # Make prediction
37
- predictions = model.predict(image_array)
38
- prediction = np.argmax(predictions, axis=1)[0]
39
-
40
- # Class mapping
41
- class_labels = {0: 'cocci', 1: 'bacilli', 2: 'spirilla'}
42
-
43
- # Log prediction details
44
- logging.debug(f"Predicted class: {class_labels[prediction]}, Confidence: {predictions[0][prediction]}")
45
-
46
- # Return prediction result
47
- return class_labels[prediction], float(predictions[0][prediction])
48
- except Exception as e:
49
- logging.error(f"Error during prediction: {str(e)}")
50
- return "Error", 0.0
51
-
52
- # Create a Gradio interface
53
- gr.Interface(
54
- fn=predict,
55
- inputs=gr.Image(type="pil", label="Upload an image"),
56
- outputs=["text", "number"],
57
  examples=[
58
  ["https://huggingface.co/datasets/yolac/BacterialMorphologyClassification/resolve/main/img%20290.jpg"],
59
  ["https://huggingface.co/datasets/yolac/BacterialMorphologyClassification/resolve/main/img%20565.jpg"],
60
  ["https://huggingface.co/datasets/yolac/BacterialMorphologyClassification/resolve/main/img%208.jpg"]
61
- ]
62
- ).launch(server_name="0.0.0.0", server_port=7862, debug=True)
 
 
 
 
 
1
  import gradio as gr
2
  import tensorflow as tf
3
+ from tensorflow.keras.models import load_model
4
+ from tensorflow.keras.preprocessing.image import img_to_array
5
  import numpy as np
6
+ from PIL import Image
7
+ import os
 
 
8
 
9
+ # Cache model during setup
10
  MODEL_PATH = "https://huggingface.co/yolac/BacterialMorphologyClassification/resolve/main/model.keras"
11
+
12
+ # Check if the model exists locally, otherwise download
13
+ if not os.path.exists(MODEL_PATH):
14
+ from huggingface_hub import hf_hub_download
15
+ print("Downloading model...")
16
+ hf_hub_download(
17
+ repo_id="yolac/BacterialMorphologyClassification",
18
+ filename="model.keras",
19
+ local_dir="./",
20
+ local_dir_use_symlinks=False
21
+ )
22
+
23
+ # Load the model
24
+ print("Loading model...")
25
+ model = load_model(MODEL_PATH)
26
+
27
+ # Define class labels
28
+ class_labels = ["Cocci", "Bacilli", "Spirilla"]
29
+
30
+ # Preprocessing function
31
  def preprocess_image(image):
32
+ image = image.resize((224, 224)) # Resize to model input size
33
+ image = img_to_array(image)
34
+ image = np.expand_dims(image, axis=0)
35
+ image = image / 255.0 # Normalize to [0, 1]
36
+ return image
37
+
38
+ # Prediction function
39
+ def classify_bacteria(image):
40
+ # Preprocess the input image
41
+ processed_image = preprocess_image(image)
42
+ # Get model predictions
43
+ predictions = model.predict(processed_image)
44
+ predicted_class = np.argmax(predictions, axis=-1)[0]
45
+ confidence = predictions[0][predicted_class]
46
+ # Return the class and confidence
47
+ return f"{class_labels[predicted_class]} (Confidence: {confidence:.2f})"
48
+
49
+ # Define Gradio interface
50
+ title = "Bacterial Morphology Classifier"
51
+ description = (
52
+ "Upload an image of bacteria, and the model will classify it into one of three types: "
53
+ "**Cocci**, **Bacilli**, or **Spirilla**."
54
+ )
55
+
56
+ # Gradio UI
57
+ interface = gr.Interface(
58
+ fn=classify_bacteria,
59
+ inputs=gr.Image(type="pil"),
60
+ outputs="text",
61
+ title=title,
62
+ description=description,
 
 
 
 
 
63
  examples=[
64
  ["https://huggingface.co/datasets/yolac/BacterialMorphologyClassification/resolve/main/img%20290.jpg"],
65
  ["https://huggingface.co/datasets/yolac/BacterialMorphologyClassification/resolve/main/img%20565.jpg"],
66
  ["https://huggingface.co/datasets/yolac/BacterialMorphologyClassification/resolve/main/img%208.jpg"]
67
+ ],
68
+ )
69
+
70
+ # Launch the app
71
+ if __name__ == "__main__":
72
+ interface.launch()