newRoop commited on
Commit
7549e78
Β·
verified Β·
1 Parent(s): 1690c98

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -67
app.py CHANGED
@@ -1,43 +1,43 @@
1
- # -*- coding: utf-8 -*-
2
- """app.py
3
-
4
- Automatically generated by Colab.
5
-
6
- Original file is located at
7
- https://colab.research.google.com/drive/1Z0eLx3x7YdED4I1Zn3QUCS31C9AzTu8I
8
- """
9
-
10
  import subprocess
11
  import sys
12
  import os
 
 
13
 
14
  def install_tensorflow():
15
  """
16
- Installs TensorFlow using pip. Handles potential errors during the installation.
 
17
  """
18
  try:
19
  print("Installing TensorFlow...")
 
20
  result = subprocess.run(
21
  [sys.executable, "-m", "pip", "install", "tensorflow"],
22
- check=True,
23
  stdout=subprocess.PIPE,
24
  stderr=subprocess.PIPE,
25
  text=True,
26
  )
27
- print("TensorFlow installed successfully.")
28
  print(result.stdout)
29
-
30
- except subprocess.CalledProcessError as e:
31
- print(f"Error installing TensorFlow: {e}")
32
- print(f"Error output (stderr):\n{e.stderr}")
33
- print("Please check your pip installation and internet connection.")
34
- print("You may need to install TensorFlow manually. Instructions can be found at:")
35
- print("https://www.tensorflow.org/install")
36
- sys.exit(1)
 
 
 
 
 
37
 
38
  except Exception as ex:
39
  print(f"An unexpected error occurred during TensorFlow installation: {ex}")
40
- sys.exit(1)
41
 
42
  def check_tensorflow_installation():
43
  """
@@ -50,12 +50,23 @@ def check_tensorflow_installation():
50
  print("TensorFlow is installed and ready to use.")
51
  return True
52
  except ImportError:
53
- print("TensorFlow is not installed.")
54
- install_tensorflow()
55
- return False
 
 
 
 
 
 
 
 
 
 
56
 
57
  if not check_tensorflow_installation():
58
- check_tensorflow_installation()
 
59
 
60
  import tensorflow as tf
61
  from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, MaxPooling2D, AveragePooling2D, Dropout
@@ -65,45 +76,10 @@ from tensorflow.keras.preprocessing.image import ImageDataGenerator
65
  from tensorflow.keras.optimizers import Adam
66
  from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
67
 
68
- # Check if running in Google Colab
69
- try:
70
- from google.colab import drive
71
- IS_COLAB = True
72
- except ImportError:
73
- IS_COLAB = False
74
- print("Not running in Google Colab. Using local file paths.")
75
-
76
- # Mount Google Drive if in Colab
77
- if IS_COLAB:
78
- try:
79
- drive.mount("/content/drive", timeout_ms=60000)
80
- except Exception as e:
81
- print(f"Error mounting drive: {e}")
82
- print("Continuing without Google Drive...")
83
- train_dir = 'train'
84
- val_dir = 'val'
85
- test_dir = 'test'
86
- else:
87
- # **IMPORTANT: Update these paths to the actual location of your data!**
88
- train_dir = "/path/to/your/data/train" # Replace with your actual path
89
- val_dir = "/path/to/your/data/val" # Replace with your actual path
90
- test_dir = "/path/to/your/data/test" # Replace with your actual path
91
-
92
- if not os.path.exists(train_dir):
93
- print(f"Error: Training data directory not found at {train_dir}")
94
- print("Please make sure the path is correct and the directory exists.")
95
- sys.exit(1)
96
- if not os.path.exists(val_dir):
97
- print(f"Error: Validation data directory not found at {val_dir}")
98
- print("Please make sure the path is correct and the directory exists.")
99
- sys.exit(1)
100
- if not os.path.exists(test_dir):
101
- print(f"Error: Test data directory not found at {test_dir}")
102
- print("Please make sure the path is correct and the directory exists.")
103
- sys.exit(1)
104
- print(f"Training data directory: {train_dir}")
105
- print(f"Validation data directory: {val_dir}")
106
- print(f"Test data directory: {test_dir}")
107
 
108
  img_height, img_width = 224, 224
109
  batch_size = 32
@@ -155,7 +131,7 @@ try:
155
  )
156
  except Exception as e:
157
  print(f"Error creating data generators: {e}")
158
- print("Please check your directory paths and data.")
159
  exit()
160
 
161
  def identity_block(X, f, filters, stage, block):
@@ -289,8 +265,9 @@ model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['ac
289
  model.summary()
290
 
291
  # Define callbacks
 
292
  checkpoint = ModelCheckpoint(
293
- filepath='best_resnet_model.keras',
294
  monitor='val_accuracy',
295
  verbose=1,
296
  save_best_only=True,
@@ -333,6 +310,10 @@ try:
333
  print(f"Test Loss: {test_loss:.4f}")
334
  print(f"Test Accuracy: {test_accuracy:.4f}")
335
 
 
 
 
 
336
  except KeyboardInterrupt:
337
  print("\nTraining interrupted by user (Ctrl+C).")
338
  print("Saving the model so far...")
@@ -340,4 +321,4 @@ except KeyboardInterrupt:
340
  print("Model saved. You can resume training later by loading this model.")
341
  except Exception as e:
342
  print(f"An error occurred during training: {e}")
343
- print("Please check your data and model configuration.")
 
 
 
 
 
 
 
 
 
 
1
  import subprocess
2
  import sys
3
  import os
4
+ import re # Import the regular expression module
5
+ import shutil # Import the shutil module
6
 
7
  def install_tensorflow():
8
  """
9
+ Installs TensorFlow using pip, targeting the *current* Python environment.
10
+ Handles potential errors during the installation. Also checks if the installation was successful.
11
  """
12
  try:
13
  print("Installing TensorFlow...")
14
+ # Use sys.executable to ensure we're using the correct pip for the current Python interpreter
15
  result = subprocess.run(
16
  [sys.executable, "-m", "pip", "install", "tensorflow"],
17
+ check=False, # Do NOT use check=True here. We'll handle errors ourselves.
18
  stdout=subprocess.PIPE,
19
  stderr=subprocess.PIPE,
20
  text=True,
21
  )
22
+ print("pip install output (stdout):")
23
  print(result.stdout)
24
+ print("pip install error output (stderr):")
25
+ print(result.stderr)
26
+
27
+ # Check for successful installation using regex
28
+ if re.search(r"Successfully installed tensorflow", result.stdout):
29
+ print("TensorFlow installation confirmed.")
30
+ return True # Indicate successful installation
31
+ else:
32
+ print(
33
+ "Warning: TensorFlow installation may not have been fully successful. "
34
+ "Please check the output above for any errors."
35
+ )
36
+ return False
37
 
38
  except Exception as ex:
39
  print(f"An unexpected error occurred during TensorFlow installation: {ex}")
40
+ return False # Indicate installation failure
41
 
42
  def check_tensorflow_installation():
43
  """
 
50
  print("TensorFlow is installed and ready to use.")
51
  return True
52
  except ImportError:
53
+ print("TensorFlow is not installed. Attempting to install...")
54
+ if install_tensorflow(): # Call install_tensorflow and check its return value
55
+ try:
56
+ import tensorflow as tf
57
+ print(f"TensorFlow version: {tf.__version__}")
58
+ print("TensorFlow is now installed and ready to use.")
59
+ return True
60
+ except ImportError:
61
+ print("TensorFlow installation failed. ImportError after installation.")
62
+ return False
63
+ else:
64
+ print("TensorFlow installation failed.")
65
+ return False
66
 
67
  if not check_tensorflow_installation():
68
+ print("TensorFlow installation failed. Exiting.")
69
+ sys.exit(1)
70
 
71
  import tensorflow as tf
72
  from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, MaxPooling2D, AveragePooling2D, Dropout
 
76
  from tensorflow.keras.optimizers import Adam
77
  from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
78
 
79
+ # Set the data directories. In Hugging Face Spaces, the data should be in the same directory.
80
+ train_dir = "train"
81
+ val_dir = "val"
82
+ test_dir = "test"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  img_height, img_width = 224, 224
85
  batch_size = 32
 
131
  )
132
  except Exception as e:
133
  print(f"Error creating data generators: {e}")
134
+ print("Please check your directory paths and data. In Hugging Face Spaces, they should be relative to the repository root.")
135
  exit()
136
 
137
  def identity_block(X, f, filters, stage, block):
 
265
  model.summary()
266
 
267
  # Define callbacks
268
+ checkpoint_path = 'best_resnet_model.keras'
269
  checkpoint = ModelCheckpoint(
270
+ filepath=checkpoint_path, # Use a simple filename
271
  monitor='val_accuracy',
272
  verbose=1,
273
  save_best_only=True,
 
310
  print(f"Test Loss: {test_loss:.4f}")
311
  print(f"Test Accuracy: {test_accuracy:.4f}")
312
 
313
+ # Save the *entire* model, not just the weights. This is crucial for Hugging Face.
314
+ model.save("resnet_model.keras") # Save as a .keras file
315
+ print("Trained model saved to resnet_model.keras")
316
+
317
  except KeyboardInterrupt:
318
  print("\nTraining interrupted by user (Ctrl+C).")
319
  print("Saving the model so far...")
 
321
  print("Model saved. You can resume training later by loading this model.")
322
  except Exception as e:
323
  print(f"An error occurred during training: {e}")
324
+ print("Please check your data and model configuration.")