Spaces:
Runtime error
Runtime error
Download app.py from newRoop/SwatiGuide: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/spaces/newRoop/SwatiGuide/resolve/main/app.py
- Command line
-
hf download hf://spaces/newRoop/SwatiGuide/app.py
-
curl -L -o app.py https://huggingface.co/spaces/newRoop/SwatiGuide/resolve/main/app.py
13.3 kB
| import subprocess | |
| import sys | |
| import os | |
| import re # Import the regular expression module | |
| import shutil # Import the shutil module | |
| def install_tensorflow(): | |
| """ | |
| Installs TensorFlow using pip, targeting the *current* Python environment. | |
| Handles potential errors during the installation. Also checks if the installation was successful. | |
| """ | |
| try: | |
| print("Installing TensorFlow...") | |
| # Use sys.executable to ensure we're using the correct pip for the current Python interpreter | |
| result = subprocess.run( | |
| [sys.executable, "-m", "pip", "install", "tensorflow"], | |
| check=False, # Do NOT use check=True here. We'll handle errors ourselves. | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.PIPE, | |
| text=True, | |
| ) | |
| print("pip install output (stdout):") | |
| print(result.stdout) | |
| print("pip install error output (stderr):") | |
| print(result.stderr) | |
| # Check for successful installation using regex | |
| if re.search(r"Successfully installed tensorflow", result.stdout): | |
| print("TensorFlow installation confirmed.") | |
| return True # Indicate successful installation | |
| else: | |
| print( | |
| "Warning: TensorFlow installation may not have been fully successful. " | |
| "Please check the output above for any errors." | |
| ) | |
| return False | |
| except Exception as ex: | |
| print(f"An unexpected error occurred during TensorFlow installation: {ex}") | |
| return False # Indicate installation failure | |
| def check_tensorflow_installation(): | |
| """ | |
| Checks if TensorFlow is installed and can be imported. | |
| If not installed, it calls the installation function. | |
| """ | |
| try: | |
| import tensorflow as tf | |
| print(f"TensorFlow version: {tf.__version__}") | |
| print("TensorFlow is installed and ready to use.") | |
| return True | |
| except ImportError: | |
| print("TensorFlow is not installed. Attempting to install...") | |
| if install_tensorflow(): # Call install_tensorflow and check its return value | |
| try: | |
| import tensorflow as tf | |
| print(f"TensorFlow version: {tf.__version__}") | |
| print("TensorFlow is now installed and ready to use.") | |
| return True | |
| except ImportError: | |
| print("TensorFlow installation failed. ImportError after installation.") | |
| return False | |
| else: | |
| print("TensorFlow installation failed.") | |
| return False | |
| if not check_tensorflow_installation(): | |
| print("TensorFlow installation failed. Exiting.") | |
| sys.exit(1) | |
| import tensorflow as tf | |
| from tensorflow.keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, MaxPooling2D, AveragePooling2D, Dropout | |
| from tensorflow.keras.models import Model | |
| from tensorflow.keras.initializers import GlorotUniform | |
| from tensorflow.keras.preprocessing.image import ImageDataGenerator | |
| from tensorflow.keras.optimizers import Adam | |
| from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping | |
| # Set the data directories. In Hugging Face Spaces, the data should be in the same directory. | |
| train_dir = "train" | |
| val_dir = "val" | |
| test_dir = "test" | |
| img_height, img_width = 224, 224 | |
| batch_size = 32 | |
| epochs = 100 | |
| num_classes = 2 | |
| # Data augmentation (optional but recommended) | |
| train_datagen = ImageDataGenerator( | |
| rescale=1. / 255, | |
| rotation_range=40, | |
| width_shift_range=0.2, | |
| height_shift_range=0.2, | |
| shear_range=0.2, | |
| zoom_range=0.2, | |
| horizontal_flip=True, | |
| fill_mode='nearest' | |
| ) | |
| val_datagen = ImageDataGenerator(rescale=1. / 255) | |
| test_datagen = ImageDataGenerator(rescale=1. / 255) | |
| # Create data generators | |
| try: | |
| train_generator = train_datagen.flow_from_directory( | |
| train_dir, | |
| target_size=(img_height, img_width), | |
| batch_size=batch_size, | |
| class_mode='categorical', | |
| shuffle=True, | |
| seed=42 | |
| ) | |
| validation_generator = val_datagen.flow_from_directory( | |
| val_dir, | |
| target_size=(img_height, img_width), | |
| batch_size=batch_size, | |
| class_mode='categorical', | |
| shuffle=False, | |
| seed=42 | |
| ) | |
| test_generator = test_datagen.flow_from_directory( | |
| test_dir, | |
| target_size=(img_height, img_width), | |
| batch_size=batch_size, | |
| class_mode='categorical', | |
| shuffle=False, | |
| seed=42 | |
| ) | |
| except Exception as e: | |
| print(f"Error creating data generators: {e}") | |
| print("Please check your directory paths and data. In Hugging Face Spaces, they should be relative to the repository root.") | |
| exit() | |
| def identity_block(X, f, filters, stage, block): | |
| """ | |
| Implementation of the identity block as defined in Figure 3 of the paper | |
| Arguments: | |
| X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) | |
| f -- integer, specifying the shape of the middle CONV's window for the main path | |
| filters -- python list of integers, defining the number of filters in the CONV layers of the main path | |
| stage -- integer, used to name the layers, depending on their position in the network | |
| block -- string/character, used to name the layers, depending on their position in the network | |
| Returns: | |
| X -- output tensor of shape (m, n_H, n_W, n_C) | |
| """ | |
| # defining name basis | |
| conv_name_base = 'conv' + str(stage) + block + '_branch' | |
| bn_name_base = 'bn' + str(stage) + block + '_branch' | |
| # Retrieve Filters | |
| F1, F2, F3 = filters | |
| # Save the input value. You'll need this later to add back to the main path. | |
| X_shortcut = X | |
| # First component of main path | |
| X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2a', kernel_initializer=GlorotUniform(seed=0))(X) | |
| X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X) | |
| X = Activation('relu')(X) | |
| # Second component of main path | |
| X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=GlorotUniform(seed=0))(X) | |
| X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X) | |
| X = Activation('relu')(X) | |
| # Third component of main path | |
| X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=GlorotUniform(seed=0))(X) | |
| X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X) | |
| # Final step: Add shortcut value to main path, and pass it through a RELU activation | |
| X = Add()([X, X_shortcut]) # X_shortcut from the beginning | |
| X = Activation('relu')(X) | |
| return X | |
| def convolutional_block(X, f, filters, stage, block, s=2): | |
| """ | |
| Implementation of the convolutional block as defined in Figure 4 | |
| Arguments: | |
| X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) | |
| f -- integer, specifying the shape of the middle CONV's window for the main path | |
| filters -- python list of integers, defining the number of filters in the CONV layers of the main path | |
| stage -- integer, used to name the layers, depending on their position in the network | |
| block -- string/character, used to name the layers, depending on their position in the network | |
| s -- integer, specifying the stride to be used | |
| Returns: | |
| X -- output tensor of shape (m, n_H, n_W, n_C) | |
| """ | |
| # defining name basis | |
| conv_name_base = 'conv' + str(stage) + block + '_branch' | |
| bn_name_base = 'bn' + str(stage) + block + '_branch' | |
| # Retrieve Filters | |
| F1, F2, F3 = filters | |
| # Save the input value | |
| X_shortcut = X | |
| # First component of main path | |
| X = Conv2D(filters=F1, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '2a', kernel_initializer=GlorotUniform(seed=0))(X) | |
| X = BatchNormalization(axis=3, name=bn_name_base + '2a')(X) | |
| X = Activation('relu')(X) | |
| # Second component of main path | |
| X = Conv2D(filters=F2, kernel_size=(f, f), strides=(1, 1), padding='same', name=conv_name_base + '2b', kernel_initializer=GlorotUniform(seed=0))(X) | |
| X = BatchNormalization(axis=3, name=bn_name_base + '2b')(X) | |
| X = Activation('relu')(X) | |
| # Third component of main path | |
| X = Conv2D(filters=F3, kernel_size=(1, 1), strides=(1, 1), padding='valid', name=conv_name_base + '2c', kernel_initializer=GlorotUniform(seed=0))(X) | |
| X = BatchNormalization(axis=3, name=bn_name_base + '2c')(X) | |
| ##### SHORTCUT PATH #### | |
| X_shortcut = Conv2D(filters=F3, kernel_size=(1, 1), strides=(s, s), padding='valid', name=conv_name_base + '1', kernel_initializer=GlorotUniform(seed=0))(X_shortcut) | |
| X_shortcut = BatchNormalization(axis=3, name=bn_name_base + '1')(X_shortcut) | |
| # Final step: Add shortcut value to main path, and pass it through a RELU activation | |
| X = Add()([X, X_shortcut]) | |
| X = Activation('relu')(X) | |
| return X | |
| def ResNetCustom(input_shape=(224, 224, 3), classes=2, num_blocks_per_stage=[2, 2, 2, 2]): | |
| """ | |
| Implementation of a custom ResNet architecture. You can specify the number of blocks per stage. | |
| Arguments: | |
| input_shape -- shape of the images of the dataset | |
| classes -- integer, number of classes | |
| num_blocks_per_stage -- a list indicating the number of identity blocks in each stage after the convolutional block | |
| Returns: | |
| model -- a Model() instance in Keras | |
| """ | |
| # Define the input as a tensor with shape input_shape | |
| X_input = Input(input_shape) | |
| # Zero-Padding | |
| X = ZeroPadding2D((3, 3))(X_input) | |
| # Stage 1 | |
| X = Conv2D(64, (7, 7), strides=(2, 2), name='conv1', kernel_initializer=GlorotUniform(seed=0))(X) | |
| X = BatchNormalization(axis=3, name='bn_conv1')(X) | |
| X = Activation('relu')(X) | |
| X = MaxPooling2D((3, 3), strides=(2, 2))(X) | |
| # Stage 2 | |
| X = convolutional_block(X, f=3, filters=[64, 64, 256], stage=2, block='a', s=1) | |
| for i in range(num_blocks_per_stage[0]): | |
| X = identity_block(X, 3, [64, 64, 256], stage=2, block=chr(ord('b') + i)) # b, c, d... | |
| # Stage 3 | |
| X = convolutional_block(X, f=3, filters=[128, 128, 512], stage=3, block='a', s=2) | |
| for i in range(num_blocks_per_stage[1]): | |
| X = identity_block(X, 3, [128, 128, 512], stage=3, block=chr(ord('b') + i)) | |
| # Stage 4 | |
| X = convolutional_block(X, f=3, filters=[256, 256, 1024], stage=4, block='a', s=2) | |
| for i in range(num_blocks_per_stage[2]): | |
| X = identity_block(X, 3, [256, 256, 1024], stage=4, block=chr(ord('b') + i)) | |
| # Stage 5 | |
| X = convolutional_block(X, f=3, filters=[512, 512, 2048], stage=5, block='a', s=2) | |
| for i in range(num_blocks_per_stage[3]): | |
| X = identity_block(X, 3, [512, 512, 2048], stage=5, block=chr(ord('b') + i)) | |
| # AVGPOOL | |
| X = AveragePooling2D(pool_size=(2, 2), name='avg_pool')(X) | |
| # FLATTEN | |
| X = Flatten()(X) | |
| # Fully connected layer | |
| X = Dense(classes, activation='softmax', name='fc' + str(classes), kernel_initializer=GlorotUniform(seed=0))(X) | |
| # Create model | |
| model = Model(inputs=X_input, outputs=X, name='ResNetCustom') | |
| return model | |
| # Build the model | |
| model = ResNetCustom(input_shape=(img_height, img_width, 3), classes=num_classes, num_blocks_per_stage=[1, 1, 1, 1]) | |
| # Compile the model | |
| optimizer = Adam(learning_rate=0.001) | |
| model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) | |
| # Model summary | |
| model.summary() | |
| # Define callbacks | |
| checkpoint_path = 'best_resnet_model.keras' | |
| checkpoint = ModelCheckpoint( | |
| filepath=checkpoint_path, # Use a simple filename | |
| monitor='val_accuracy', | |
| verbose=1, | |
| save_best_only=True, | |
| mode='max' | |
| ) | |
| reduce_lr = ReduceLROnPlateau( | |
| monitor='val_loss', | |
| factor=0.2, | |
| patience=5, | |
| verbose=1, | |
| mode='min', | |
| min_lr=1e-6 | |
| ) | |
| early_stopping = EarlyStopping( | |
| monitor='val_loss', | |
| patience=10, | |
| restore_best_weights=True, | |
| verbose=1 | |
| ) | |
| callbacks = [checkpoint, reduce_lr, early_stopping] | |
| # Train the model | |
| try: | |
| history = model.fit( | |
| train_generator, | |
| steps_per_epoch=train_generator.samples // train_generator.batch_size, | |
| epochs=epochs, | |
| validation_data=validation_generator, | |
| validation_steps=validation_generator.samples // validation_generator.batch_size, | |
| callbacks=callbacks, | |
| verbose=1 | |
| ) | |
| print("Training complete!") | |
| # Evaluate the model on the test set | |
| test_loss, test_accuracy = model.evaluate(test_generator, steps=test_generator.samples // test_generator.batch_size, verbose=1) | |
| print(f"Test Loss: {test_loss:.4f}") | |
| print(f"Test Accuracy: {test_accuracy:.4f}") | |
| # Save the *entire* model, not just the weights. This is crucial for Hugging Face. | |
| model.save("resnet_model.keras") # Save as a .keras file | |
| print("Trained model saved to resnet_model.keras") | |
| except KeyboardInterrupt: | |
| print("\nTraining interrupted by user (Ctrl+C).") | |
| print("Saving the model so far...") | |
| model.save('interrupted_resnet_model.keras') | |
| print("Model saved. You can resume training later by loading this model.") | |
| except Exception as e: | |
| print(f"An error occurred during training: {e}") | |
| print("Please check your data and model configuration.") | |
| print("Please check your data and model configuration.") | |