Ahmedhassan54 commited on
Commit
36586fd
ยท
verified ยท
1 Parent(s): a0d6908

Upload 4 files

Browse files
Files changed (2) hide show
  1. app.py +35 -65
  2. requirements.txt +3 -2
app.py CHANGED
@@ -15,64 +15,52 @@ logger = logging.getLogger(__name__)
15
  MODEL_REPO = "Ahmedhassan54/Image-Classification"
16
  MODEL_FILE = "best_model.h5"
17
 
18
- # Initialize model to None
19
  model = None
20
 
21
  def load_model():
22
  global model
23
  try:
24
- logger.info("โณ Downloading model...")
25
  model_path = hf_hub_download(
26
  repo_id=MODEL_REPO,
27
  filename=MODEL_FILE,
28
  cache_dir=".",
29
  force_download=True
30
  )
31
- logger.info(f"๐Ÿ“ Model path: {model_path}")
32
 
33
- # Verify file exists
34
- if not os.path.exists(model_path):
35
- raise FileNotFoundError(f"Model file not found at {model_path}")
36
-
37
- logger.info("๐Ÿ”„ Loading TensorFlow model...")
38
  model = tf.keras.models.load_model(model_path)
39
- logger.info("โœ… Model loaded successfully!")
40
-
41
  except Exception as e:
42
- logger.error(f"โŒ Model loading failed: {str(e)}")
43
  model = None
44
- raise gr.Error(f"Model loading failed. Check logs for details.")
45
 
46
- # Load model when app starts
47
  load_model()
48
 
49
  def classify_image(image):
50
  try:
51
  if image is None:
52
- raise gr.Error("Please upload an image first")
53
 
54
- logger.info("๐Ÿ–ผ๏ธ Processing image...")
55
-
56
  # Convert to PIL Image if numpy array
57
  if isinstance(image, np.ndarray):
58
  image = Image.fromarray(image)
59
 
60
- # Resize and normalize
61
  image = image.resize((150, 150))
62
  img_array = np.array(image) / 255.0
63
  if len(img_array.shape) == 3:
64
  img_array = np.expand_dims(img_array, axis=0)
65
 
66
- logger.info(f"๐Ÿ“Š Input shape: {img_array.shape}")
67
-
68
- if model is None:
69
- raise gr.Error("Model not loaded - using demo mode")
70
- return {"Cat": 0.5, "Dog": 0.5}, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})
 
71
 
72
- pred = model.predict(img_array, verbose=0)
73
- confidence = float(pred[0][0])
74
- logger.info(f"๐Ÿ”ฎ Prediction confidence: {confidence}")
75
-
76
  results = {
77
  "Cat": round(1 - confidence, 4),
78
  "Dog": round(confidence, 4)
@@ -86,61 +74,43 @@ def classify_image(image):
86
  return results, plot_data
87
 
88
  except Exception as e:
89
- logger.error(f"๐Ÿ’ฅ Classification error: {str(e)}")
90
- raise gr.Error(f"Error processing image: {str(e)}")
91
-
92
- css = """
93
- .gradio-container { max-width: 900px; margin: auto; }
94
- footer { visibility: hidden; }
95
- .progress-bar { color: #ff4d4d !important; }
96
- """
97
 
98
- with gr.Blocks(css=css, theme=gr.themes.Soft()) as demo:
99
- gr.Markdown("""
100
- # ๐Ÿพ Cat vs Dog Classifier ๐Ÿฆฎ
101
- Upload an image to classify whether it's a cat or dog
102
- """)
103
 
104
  with gr.Row():
105
  with gr.Column():
106
- image_input = gr.Image(label="Upload Image", type="pil")
107
- with gr.Row():
108
- submit_btn = gr.Button("Classify ๐Ÿš€", variant="primary")
109
- clear_btn = gr.Button("Clear ๐Ÿ—‘๏ธ")
110
 
111
  with gr.Column():
112
- label_output = gr.Label(label="Predictions")
113
- confidence_bar = gr.BarPlot(
114
  pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]}),
115
- x="Class", y="Confidence", y_lim=[0,1],
116
- title="Confidence Scores", width=400, height=300
117
  )
118
 
119
- # Examples
 
 
 
 
 
 
 
120
  gr.Examples(
121
  examples=[
122
  ["https://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"],
123
  ["https://upload.wikimedia.org/wikipedia/commons/d/d9/Collage_of_Nine_Dogs.jpg"]
124
  ],
125
- inputs=image_input,
126
- outputs=[label_output, confidence_bar],
127
  fn=classify_image,
128
  cache_examples=True
129
  )
130
-
131
- # Button actions
132
- submit_btn.click(
133
- fn=classify_image,
134
- inputs=image_input,
135
- outputs=[label_output, confidence_bar],
136
- api_name="predict"
137
- )
138
-
139
- clear_btn.click(
140
- fn=lambda: [None, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})],
141
- inputs=None,
142
- outputs=[image_input, confidence_bar]
143
- )
144
 
145
  if __name__ == "__main__":
146
- demo.launch(debug=True)
 
15
  MODEL_REPO = "Ahmedhassan54/Image-Classification"
16
  MODEL_FILE = "best_model.h5"
17
 
18
+ # Initialize model
19
  model = None
20
 
21
  def load_model():
22
  global model
23
  try:
24
+ logger.info("Downloading model...")
25
  model_path = hf_hub_download(
26
  repo_id=MODEL_REPO,
27
  filename=MODEL_FILE,
28
  cache_dir=".",
29
  force_download=True
30
  )
31
+ logger.info(f"Model path: {model_path}")
32
 
 
 
 
 
 
33
  model = tf.keras.models.load_model(model_path)
34
+ logger.info("Model loaded successfully!")
 
35
  except Exception as e:
36
+ logger.error(f"Model loading failed: {str(e)}")
37
  model = None
 
38
 
39
+ # Load model at startup
40
  load_model()
41
 
42
  def classify_image(image):
43
  try:
44
  if image is None:
45
+ return {"Cat": 0.5, "Dog": 0.5}, pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]})
46
 
 
 
47
  # Convert to PIL Image if numpy array
48
  if isinstance(image, np.ndarray):
49
  image = Image.fromarray(image)
50
 
51
+ # Preprocess
52
  image = image.resize((150, 150))
53
  img_array = np.array(image) / 255.0
54
  if len(img_array.shape) == 3:
55
  img_array = np.expand_dims(img_array, axis=0)
56
 
57
+ # Predict
58
+ if model is not None:
59
+ pred = model.predict(img_array, verbose=0)
60
+ confidence = float(pred[0][0])
61
+ else:
62
+ confidence = 0.75 # Demo value
63
 
 
 
 
 
64
  results = {
65
  "Cat": round(1 - confidence, 4),
66
  "Dog": round(confidence, 4)
 
74
  return results, plot_data
75
 
76
  except Exception as e:
77
+ logger.error(f"Error: {str(e)}")
78
+ return {"Error": str(e)}, pd.DataFrame()
 
 
 
 
 
 
79
 
80
+ # Interface
81
+ with gr.Blocks() as demo:
82
+ gr.Markdown("# ๐Ÿพ Cat vs Dog Classifier ๐Ÿฆฎ")
 
 
83
 
84
  with gr.Row():
85
  with gr.Column():
86
+ img_input = gr.Image(type="pil")
87
+ classify_btn = gr.Button("Classify", variant="primary")
 
 
88
 
89
  with gr.Column():
90
+ label_out = gr.Label(num_top_classes=2)
91
+ plot_out = gr.BarPlot(
92
  pd.DataFrame({'Class': ['Cat', 'Dog'], 'Confidence': [0.5, 0.5]}),
93
+ x="Class", y="Confidence", y_lim=[0,1]
 
94
  )
95
 
96
+ # Fixed button click handler - removed api_name
97
+ classify_btn.click(
98
+ fn=classify_image,
99
+ inputs=img_input,
100
+ outputs=[label_out, plot_out]
101
+ )
102
+
103
+ # Examples section
104
  gr.Examples(
105
  examples=[
106
  ["https://upload.wikimedia.org/wikipedia/commons/1/15/Cat_August_2010-4.jpg"],
107
  ["https://upload.wikimedia.org/wikipedia/commons/d/d9/Collage_of_Nine_Dogs.jpg"]
108
  ],
109
+ inputs=img_input,
110
+ outputs=[label_out, plot_out],
111
  fn=classify_image,
112
  cache_examples=True
113
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  if __name__ == "__main__":
116
+ demo.launch()
requirements.txt CHANGED
@@ -1,5 +1,6 @@
1
- tensorflow
2
  gradio
 
3
  pillow
4
- numpy
5
  huggingface-hub
 
 
 
1
  gradio
2
+ tensorflow
3
  pillow
4
+ pandas
5
  huggingface-hub
6
+ numpy