Ahmedhassan54 commited on
Commit
217a3bc
·
verified ·
1 Parent(s): 6d71650

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -12
app.py CHANGED
@@ -7,18 +7,18 @@ import os
7
  import pandas as pd
8
  import logging
9
 
10
- # Disable GPU if not available (for Hugging Face Spaces)
11
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
12
 
13
- # Setup logging
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
17
- # Configuration
18
  MODEL_REPO = "Ahmedhassan54/Image-Classification-Model"
19
  MODEL_FILE = "best_model.keras"
20
 
21
- # Initialize model
22
  model = None
23
 
24
  def load_model():
@@ -33,7 +33,7 @@ def load_model():
33
  )
34
  logger.info(f"Model path: {model_path}")
35
 
36
- # Explicitly disable GPU
37
  with tf.device('/CPU:0'):
38
  model = tf.keras.models.load_model(model_path)
39
  logger.info("Model loaded successfully!")
@@ -41,7 +41,7 @@ def load_model():
41
  logger.error(f"Model loading failed: {str(e)}")
42
  model = None
43
 
44
- # Load model at startup
45
  load_model()
46
 
47
  def classify_image(image):
@@ -49,23 +49,23 @@ def classify_image(image):
49
  if image is None:
50
  return {"Cat": 0.5, "Dog": 0.5}, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})
51
 
52
- # Convert to PIL Image if numpy array
53
  if isinstance(image, np.ndarray):
54
  image = Image.fromarray(image.astype('uint8'))
55
 
56
- # Preprocess
57
  image = image.resize((150, 150))
58
  img_array = np.array(image) / 255.0
59
  if len(img_array.shape) == 3:
60
  img_array = np.expand_dims(img_array, axis=0)
61
 
62
- # Predict
63
  if model is not None:
64
  with tf.device('/CPU:0'):
65
  pred = model.predict(img_array, verbose=0)
66
  confidence = float(pred[0][0])
67
  else:
68
- confidence = 0.75 # Demo value
69
 
70
  results = {
71
  "Cat": round(1 - confidence, 4),
@@ -83,7 +83,7 @@ def classify_image(image):
83
  logger.error(f"Error: {str(e)}")
84
  return {"Error": str(e)}, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})
85
 
86
- # Interface
87
  with gr.Blocks() as demo:
88
  gr.Markdown("# 🐾 Cat vs Dog Classifier 🦮")
89
 
@@ -105,7 +105,7 @@ with gr.Blocks() as demo:
105
  outputs=[label_out, plot_out]
106
  )
107
 
108
- # Examples section
109
  gr.Examples(
110
  examples=[
111
  ["https://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"],
 
7
  import pandas as pd
8
  import logging
9
 
10
+
11
  os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
12
 
13
+
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
17
+
18
  MODEL_REPO = "Ahmedhassan54/Image-Classification-Model"
19
  MODEL_FILE = "best_model.keras"
20
 
21
+
22
  model = None
23
 
24
  def load_model():
 
33
  )
34
  logger.info(f"Model path: {model_path}")
35
 
36
+
37
  with tf.device('/CPU:0'):
38
  model = tf.keras.models.load_model(model_path)
39
  logger.info("Model loaded successfully!")
 
41
  logger.error(f"Model loading failed: {str(e)}")
42
  model = None
43
 
44
+
45
  load_model()
46
 
47
  def classify_image(image):
 
49
  if image is None:
50
  return {"Cat": 0.5, "Dog": 0.5}, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})
51
 
52
+
53
  if isinstance(image, np.ndarray):
54
  image = Image.fromarray(image.astype('uint8'))
55
 
56
+
57
  image = image.resize((150, 150))
58
  img_array = np.array(image) / 255.0
59
  if len(img_array.shape) == 3:
60
  img_array = np.expand_dims(img_array, axis=0)
61
 
62
+
63
  if model is not None:
64
  with tf.device('/CPU:0'):
65
  pred = model.predict(img_array, verbose=0)
66
  confidence = float(pred[0][0])
67
  else:
68
+ confidence = 0.75
69
 
70
  results = {
71
  "Cat": round(1 - confidence, 4),
 
83
  logger.error(f"Error: {str(e)}")
84
  return {"Error": str(e)}, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})
85
 
86
+
87
  with gr.Blocks() as demo:
88
  gr.Markdown("# 🐾 Cat vs Dog Classifier 🦮")
89
 
 
105
  outputs=[label_out, plot_out]
106
  )
107
 
108
+
109
  gr.Examples(
110
  examples=[
111
  ["https://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"],