Ahmedhassan54 commited on
Commit
ae329be
·
verified ·
1 Parent(s): f52233f

Upload 4 files

Browse files
Files changed (2) hide show
  1. app.py +15 -16
  2. model.py +19 -35
app.py CHANGED
@@ -6,14 +6,14 @@ from PIL import Image
6
  from huggingface_hub import hf_hub_download
7
  import os
8
 
9
- # Configuration
10
- MODEL_REPO = "Ahmedhassan54/Image-Classification" # Replace with your HF username and repo
11
  MODEL_FILE = "best_model.h5"
12
 
13
- # Download model from Hugging Face Hub
14
  def load_model_from_hf():
15
  try:
16
- # Check if model exists locally first
17
  if not os.path.exists(MODEL_FILE):
18
  print("Downloading model from Hugging Face Hub...")
19
  model_path = hf_hub_download(
@@ -21,10 +21,10 @@ def load_model_from_hf():
21
  filename=MODEL_FILE,
22
  cache_dir="."
23
  )
24
- # Copy to current directory for easier access
25
  os.system(f"cp {model_path} {MODEL_FILE}")
26
 
27
- # Load the model
28
  model = tf.keras.models.load_model(MODEL_FILE)
29
  print("Model loaded successfully!")
30
  return model
@@ -32,22 +32,21 @@ def load_model_from_hf():
32
  print(f"Error loading model: {str(e)}")
33
  raise
34
 
35
- # Load the model when the app starts
36
  model = load_model_from_hf()
37
 
38
- # Image classification function
39
  def classify_image(image):
40
  try:
41
- # Preprocess the image
42
- image = image.resize((150, 150)) # Match model's expected input size
43
- image_array = np.array(image) / 255.0 # Normalize
44
- image_array = np.expand_dims(image_array, axis=0) # Add batch dimension
45
 
46
- # Make prediction
47
  prediction = model.predict(image_array)
48
  confidence = float(prediction[0][0])
49
 
50
- # Format results
51
  if confidence > 0.5:
52
  return {
53
  "Dog": confidence * 100,
@@ -61,7 +60,7 @@ def classify_image(image):
61
  except Exception as e:
62
  return f"Error processing image: {str(e)}"
63
 
64
- # Gradio interface
65
  demo = gr.Interface(
66
  fn=classify_image,
67
  inputs=gr.Image(type="pil", label="Upload Image"),
@@ -75,6 +74,6 @@ demo = gr.Interface(
75
  allow_flagging="never"
76
  )
77
 
78
- # Launch the app
79
  if __name__ == "__main__":
80
  demo.launch(debug=True, server_port=7860)
 
6
  from huggingface_hub import hf_hub_download
7
  import os
8
 
9
+
10
+ MODEL_REPO = "Ahmedhassan54/Image-Classification"
11
  MODEL_FILE = "best_model.h5"
12
 
13
+
14
  def load_model_from_hf():
15
  try:
16
+
17
  if not os.path.exists(MODEL_FILE):
18
  print("Downloading model from Hugging Face Hub...")
19
  model_path = hf_hub_download(
 
21
  filename=MODEL_FILE,
22
  cache_dir="."
23
  )
24
+
25
  os.system(f"cp {model_path} {MODEL_FILE}")
26
 
27
+
28
  model = tf.keras.models.load_model(MODEL_FILE)
29
  print("Model loaded successfully!")
30
  return model
 
32
  print(f"Error loading model: {str(e)}")
33
  raise
34
 
35
+
36
  model = load_model_from_hf()
37
 
38
+
39
  def classify_image(image):
40
  try:
41
+
42
+ image = image.resize((150, 150))
43
+ image_array = np.array(image) / 255.0
44
+ image_array = np.expand_dims(image_array, axis=0)
45
 
46
+
47
  prediction = model.predict(image_array)
48
  confidence = float(prediction[0][0])
49
 
 
50
  if confidence > 0.5:
51
  return {
52
  "Dog": confidence * 100,
 
60
  except Exception as e:
61
  return f"Error processing image: {str(e)}"
62
 
63
+
64
  demo = gr.Interface(
65
  fn=classify_image,
66
  inputs=gr.Image(type="pil", label="Upload Image"),
 
74
  allow_flagging="never"
75
  )
76
 
77
+
78
  if __name__ == "__main__":
79
  demo.launch(debug=True, server_port=7860)
model.py CHANGED
@@ -1,11 +1,6 @@
1
- # Image Classification for Cat vs Dog Dataset (Fixed Version)
2
- # Run in Google Colab with GPU
3
 
4
- ## 1. Setup Environment
5
- !nvidia-smi
6
- !pip install tensorboard-plugin-profile
7
 
8
- ## 2. Import Libraries
9
  import tensorflow as tf
10
  from tensorflow.keras import layers, models, callbacks
11
  from tensorflow.keras.preprocessing.image import ImageDataGenerator
@@ -22,49 +17,40 @@ from pathlib import Path
22
 
23
  print("TensorFlow version:", tf.__version__)
24
 
25
- ## 3. Upload and Reorganize Your Dataset
26
- # Upload your zip file
27
  uploaded = files.upload()
28
  zip_filename = list(uploaded.keys())[0]
29
 
30
- # Extract the zip file
31
  with zipfile.ZipFile(zip_filename, 'r') as zip_ref:
32
  zip_ref.extractall('extracted_dataset')
33
 
34
- # Verify extraction
35
- !ls extracted_dataset
36
 
37
- # Your dataset has images directly in custom_dataset/train/ (not in cat/dog subfolders)
38
- # We need to reorganize them into proper class folders
39
  def organize_dataset(input_dir, output_dir):
40
- # Create class directories
41
  os.makedirs(os.path.join(output_dir, 'cat'), exist_ok=True)
42
  os.makedirs(os.path.join(output_dir, 'dog'), exist_ok=True)
43
 
44
- # Move cat images
45
  for file in Path(input_dir).glob('cat.*.jpg'):
46
  move(str(file), os.path.join(output_dir, 'cat', file.name))
47
 
48
- # Move dog images
49
  for file in Path(input_dir).glob('dog.*.jpg'):
50
  move(str(file), os.path.join(output_dir, 'dog', file.name))
51
 
52
- # Reorganize the dataset
53
  input_path = 'extracted_dataset/custom_dataset/train'
54
  output_path = 'organized_dataset/train'
55
  organize_dataset(input_path, output_path)
56
 
57
- # Verify the new structure
58
- !ls organized_dataset/train
59
- !ls organized_dataset/train/cat | head -5
60
- !ls organized_dataset/train/dog | head -5
61
 
62
- ## 4. Create Data Generators
63
- # Parameters
64
  IMG_SIZE = (150, 150)
65
  BATCH_SIZE = 32
66
 
67
- # Data generators with augmentation
68
  train_datagen = ImageDataGenerator(
69
  rescale=1./255,
70
  rotation_range=20,
@@ -73,10 +59,10 @@ train_datagen = ImageDataGenerator(
73
  shear_range=0.2,
74
  zoom_range=0.2,
75
  horizontal_flip=True,
76
- validation_split=0.2 # 20% for validation
77
  )
78
 
79
- # Training generator
80
  train_generator = train_datagen.flow_from_directory(
81
  'organized_dataset/train',
82
  target_size=IMG_SIZE,
@@ -86,7 +72,7 @@ train_generator = train_datagen.flow_from_directory(
86
  shuffle=True
87
  )
88
 
89
- # Validation generator
90
  validation_generator = train_datagen.flow_from_directory(
91
  'organized_dataset/train',
92
  target_size=IMG_SIZE,
@@ -96,13 +82,12 @@ validation_generator = train_datagen.flow_from_directory(
96
  shuffle=True
97
  )
98
 
99
- # Get class names
100
  class_names = list(train_generator.class_indices.keys())
101
  print("\nDetected classes:", class_names)
102
  print("Number of training samples:", train_generator.samples)
103
  print("Number of validation samples:", validation_generator.samples)
104
 
105
- # Visualize samples
106
  plt.figure(figsize=(12, 9))
107
  for i in range(9):
108
  img, label = next(train_generator)
@@ -113,7 +98,7 @@ for i in range(9):
113
  plt.suptitle("Sample Training Images")
114
  plt.show()
115
 
116
- ## 5. Build Model
117
  def build_model(input_shape):
118
  model = models.Sequential([
119
  layers.Conv2D(32, (3,3), activation='relu', input_shape=input_shape),
@@ -141,7 +126,7 @@ def build_model(input_shape):
141
  model = build_model(input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3))
142
  model.summary()
143
 
144
- ## 6. Train Model
145
  log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
146
 
147
  callbacks = [
@@ -160,8 +145,7 @@ history = model.fit(
160
  callbacks=callbacks
161
  )
162
 
163
- ## 7. Evaluate Model
164
- # Plot training history
165
  plt.figure(figsize=(12, 4))
166
  plt.subplot(1, 2, 1)
167
  plt.plot(history.history['accuracy'], label='Train')
@@ -176,10 +160,10 @@ plt.title('Loss')
176
  plt.legend()
177
  plt.show()
178
 
179
- ## 8. Save Model
180
  model.save('cat_dog_classifier.h5')
181
 
182
- # Convert to TFLite
183
  converter = tf.lite.TFLiteConverter.from_keras_model(model)
184
  tflite_model = converter.convert()
185
  with open('cat_dog.tflite', 'wb') as f:
 
 
 
1
 
 
 
 
2
 
3
+
4
  import tensorflow as tf
5
  from tensorflow.keras import layers, models, callbacks
6
  from tensorflow.keras.preprocessing.image import ImageDataGenerator
 
17
 
18
  print("TensorFlow version:", tf.__version__)
19
 
20
+
 
21
  uploaded = files.upload()
22
  zip_filename = list(uploaded.keys())[0]
23
 
 
24
  with zipfile.ZipFile(zip_filename, 'r') as zip_ref:
25
  zip_ref.extractall('extracted_dataset')
26
 
 
 
27
 
28
+
29
+
30
  def organize_dataset(input_dir, output_dir):
31
+
32
  os.makedirs(os.path.join(output_dir, 'cat'), exist_ok=True)
33
  os.makedirs(os.path.join(output_dir, 'dog'), exist_ok=True)
34
 
35
+
36
  for file in Path(input_dir).glob('cat.*.jpg'):
37
  move(str(file), os.path.join(output_dir, 'cat', file.name))
38
 
39
+
40
  for file in Path(input_dir).glob('dog.*.jpg'):
41
  move(str(file), os.path.join(output_dir, 'dog', file.name))
42
 
43
+
44
  input_path = 'extracted_dataset/custom_dataset/train'
45
  output_path = 'organized_dataset/train'
46
  organize_dataset(input_path, output_path)
47
 
 
 
 
 
48
 
49
+
 
50
  IMG_SIZE = (150, 150)
51
  BATCH_SIZE = 32
52
 
53
+
54
  train_datagen = ImageDataGenerator(
55
  rescale=1./255,
56
  rotation_range=20,
 
59
  shear_range=0.2,
60
  zoom_range=0.2,
61
  horizontal_flip=True,
62
+ validation_split=0.2
63
  )
64
 
65
+
66
  train_generator = train_datagen.flow_from_directory(
67
  'organized_dataset/train',
68
  target_size=IMG_SIZE,
 
72
  shuffle=True
73
  )
74
 
75
+
76
  validation_generator = train_datagen.flow_from_directory(
77
  'organized_dataset/train',
78
  target_size=IMG_SIZE,
 
82
  shuffle=True
83
  )
84
 
 
85
  class_names = list(train_generator.class_indices.keys())
86
  print("\nDetected classes:", class_names)
87
  print("Number of training samples:", train_generator.samples)
88
  print("Number of validation samples:", validation_generator.samples)
89
 
90
+
91
  plt.figure(figsize=(12, 9))
92
  for i in range(9):
93
  img, label = next(train_generator)
 
98
  plt.suptitle("Sample Training Images")
99
  plt.show()
100
 
101
+
102
  def build_model(input_shape):
103
  model = models.Sequential([
104
  layers.Conv2D(32, (3,3), activation='relu', input_shape=input_shape),
 
126
  model = build_model(input_shape=(IMG_SIZE[0], IMG_SIZE[1], 3))
127
  model.summary()
128
 
129
+
130
  log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
131
 
132
  callbacks = [
 
145
  callbacks=callbacks
146
  )
147
 
148
+
 
149
  plt.figure(figsize=(12, 4))
150
  plt.subplot(1, 2, 1)
151
  plt.plot(history.history['accuracy'], label='Train')
 
160
  plt.legend()
161
  plt.show()
162
 
163
+
164
  model.save('cat_dog_classifier.h5')
165
 
166
+
167
  converter = tf.lite.TFLiteConverter.from_keras_model(model)
168
  tflite_model = converter.convert()
169
  with open('cat_dog.tflite', 'wb') as f: