Ahmedhassan54 commited on
Commit
3ba7ae0
·
verified ·
1 Parent(s): 78cdd85

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -47
app.py CHANGED
@@ -5,6 +5,11 @@ from PIL import Image
5
  from huggingface_hub import hf_hub_download
6
  import os
7
  import pandas as pd
 
 
 
 
 
8
 
9
  # Configuration
10
  MODEL_REPO = "Ahmedhassan54/Image-Classification"
@@ -13,67 +18,77 @@ MODEL_FILE = "best_model.h5"
13
  # Download model from Hugging Face Hub
14
  def load_model_from_hf():
15
  try:
16
- print("Attempting to load model...")
17
- if not os.path.exists(MODEL_FILE):
18
- print("Model file not found locally. Downloading...")
19
- model_path = hf_hub_download(
20
- repo_id=MODEL_REPO,
21
- filename=MODEL_FILE,
22
- cache_dir="."
23
- )
24
- print(f"Model downloaded to: {model_path}")
25
- os.system(f"cp {model_path} {MODEL_FILE}")
26
- print("Model copied to working directory")
27
 
28
- print("Loading model...")
29
- model = tf.keras.models.load_model(MODEL_FILE)
30
- print("Model loaded successfully!")
 
31
  return model
 
32
  except Exception as e:
33
- print(f"Model loading failed: {str(e)}")
34
- raise gr.Error(f"Model loading failed: {str(e)}")
35
 
36
  # Load model when the app starts
37
  try:
38
  model = load_model_from_hf()
39
- except:
40
  model = None
41
- print("Proceeding without model - for debugging purposes")
42
 
43
  def classify_image(image):
44
  try:
45
- print("\nClassification started...")
46
 
47
  # Debug: Check input type
48
- print(f"Input type: {type(image)}")
 
 
 
49
 
50
  # Convert image if needed
51
  if isinstance(image, np.ndarray):
52
- print("Converting numpy array to PIL Image")
53
  image = Image.fromarray(image)
 
 
54
 
55
  # Preprocess image
56
- print("Preprocessing image...")
57
  image = image.resize((150, 150))
58
  image_array = np.array(image) / 255.0
59
- image_array = np.expand_dims(image_array, axis=0)
 
 
 
 
 
60
 
61
  # Make prediction
62
- print("Making prediction...")
63
  if model is None:
64
- # For debugging when model fails to load
65
- confidence = 0.75 # Mock value
66
- print("Using mock prediction (model not loaded)")
67
- else:
68
- prediction = model.predict(image_array, verbose=0)
69
- confidence = float(prediction[0][0])
70
 
71
- print(f"Raw confidence: {confidence}")
 
 
 
 
72
 
73
  # Format outputs
74
  label_output = {
75
- "Cat": 1 - confidence,
76
- "Dog": confidence
77
  }
78
 
79
  # Create dataframe for bar plot
@@ -82,14 +97,14 @@ def classify_image(image):
82
  'Confidence': [1 - confidence, confidence]
83
  })
84
 
85
- print("Classification successful!")
86
- print(f"Results: {label_output}")
87
 
88
  return label_output, plot_data
89
 
90
  except Exception as e:
91
- print(f"Error during classification: {str(e)}")
92
- raise gr.Error(f"Classification error: {str(e)}")
93
 
94
  # Custom CSS
95
  css = """
@@ -99,13 +114,9 @@ css = """
99
  footer {
100
  visibility: hidden
101
  }
102
- .animate-pulse {
103
- animation: pulse 2s infinite;
104
- }
105
- @keyframes pulse {
106
- 0% { opacity: 1; }
107
- 50% { opacity: 0.5; }
108
- 100% { opacity: 1; }
109
  }
110
  """
111
 
@@ -158,12 +169,12 @@ with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
158
  )
159
 
160
  clear_btn.click(
161
- fn=lambda: [None, None, None],
162
  inputs=None,
163
- outputs=[image_input, label_output, confidence_bar],
164
  show_progress=False
165
  )
166
 
167
- # For debugging in Hugging Face Spaces
168
  if __name__ == "__main__":
169
  demo.launch(debug=True)
 
5
  from huggingface_hub import hf_hub_download
6
  import os
7
  import pandas as pd
8
+ import logging
9
+
10
+ # Setup logging
11
+ logging.basicConfig(level=logging.INFO)
12
+ logger = logging.getLogger(__name__)
13
 
14
  # Configuration
15
  MODEL_REPO = "Ahmedhassan54/Image-Classification"
 
18
  # Download model from Hugging Face Hub
19
  def load_model_from_hf():
20
  try:
21
+ logger.info("Attempting to load model...")
22
+
23
+ # Check if model exists in cache
24
+ model_path = hf_hub_download(
25
+ repo_id=MODEL_REPO,
26
+ filename=MODEL_FILE,
27
+ cache_dir=".",
28
+ force_download=True # Ensure fresh download
29
+ )
30
+ logger.info(f"Model downloaded to: {model_path}")
 
31
 
32
+ # Load model
33
+ logger.info("Loading model...")
34
+ model = tf.keras.models.load_model(model_path)
35
+ logger.info("Model loaded successfully!")
36
  return model
37
+
38
  except Exception as e:
39
+ logger.error(f"Model loading failed: {str(e)}")
40
+ raise gr.Error(f"⚠️ Model loading failed: {str(e)}. Check the logs for details.")
41
 
42
  # Load model when the app starts
43
  try:
44
  model = load_model_from_hf()
45
+ except Exception as e:
46
  model = None
47
+ logger.error(f"Proceeding without model due to: {str(e)}")
48
 
49
  def classify_image(image):
50
  try:
51
+ logger.info("\nClassification started...")
52
 
53
  # Debug: Check input type
54
+ logger.info(f"Input type: {type(image)}")
55
+
56
+ if image is None:
57
+ raise ValueError("No image provided")
58
 
59
  # Convert image if needed
60
  if isinstance(image, np.ndarray):
61
+ logger.info("Converting numpy array to PIL Image")
62
  image = Image.fromarray(image)
63
+ elif not isinstance(image, Image.Image):
64
+ raise ValueError(f"Unexpected image type: {type(image)}")
65
 
66
  # Preprocess image
67
+ logger.info("Preprocessing image...")
68
  image = image.resize((150, 150))
69
  image_array = np.array(image) / 255.0
70
+
71
+ # Add batch dimension
72
+ if len(image_array.shape) == 3:
73
+ image_array = np.expand_dims(image_array, axis=0)
74
+
75
+ logger.info(f"Image array shape: {image_array.shape}")
76
 
77
  # Make prediction
78
+ logger.info("Making prediction...")
79
  if model is None:
80
+ raise gr.Error("Model failed to load. Cannot make predictions.")
 
 
 
 
 
81
 
82
+ prediction = model.predict(image_array, verbose=0)
83
+ logger.info(f"Raw prediction: {prediction}")
84
+
85
+ confidence = float(prediction[0][0])
86
+ logger.info(f"Confidence score: {confidence}")
87
 
88
  # Format outputs
89
  label_output = {
90
+ "Cat": round(1 - confidence, 4),
91
+ "Dog": round(confidence, 4)
92
  }
93
 
94
  # Create dataframe for bar plot
 
97
  'Confidence': [1 - confidence, confidence]
98
  })
99
 
100
+ logger.info("Classification successful!")
101
+ logger.info(f"Results: {label_output}")
102
 
103
  return label_output, plot_data
104
 
105
  except Exception as e:
106
+ logger.error(f"Error during classification: {str(e)}", exc_info=True)
107
+ raise gr.Error(f"🔴 Classification failed: {str(e)}")
108
 
109
  # Custom CSS
110
  css = """
 
114
  footer {
115
  visibility: hidden
116
  }
117
+ .error-message {
118
+ color: red !important;
119
+ font-weight: bold !important;
 
 
 
 
120
  }
121
  """
122
 
 
169
  )
170
 
171
  clear_btn.click(
172
+ fn=lambda: [None, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})],
173
  inputs=None,
174
+ outputs=[image_input, confidence_bar],
175
  show_progress=False
176
  )
177
 
178
+ # Launch the app
179
  if __name__ == "__main__":
180
  demo.launch(debug=True)