Yusuf Rahman (k22040245) commited on
Commit
bb82af6
·
unverified ·
2 Parent(s): 3edadc3 e6d94e8

Merge pull request #10 from K23064919/develop

Browse files
dataPrep/data_preparation.py CHANGED
@@ -45,8 +45,9 @@ if torch.cuda.is_available():
45
 
46
 
47
  # ----- ClearML Setup -----
 
48
  task = Task.init(
49
- project_name='Small Group Project',
50
  task_name='Data Preparation',
51
  task_type=Task.TaskTypes.data_processing
52
  )
@@ -74,15 +75,15 @@ task.connect({
74
  })
75
 
76
  # ----- Load a subset from a given dataset & track with ClearML -----
77
- data_plants, prototyping_dataset, features, clearml_dataset = make_subset(
78
- DATASET_LINK, DATASET_SUBSET_RATIO, clearml_logger
79
  )
80
 
81
 
82
  # ---- Exploratory data analysis (EDA) ----
83
 
84
  # Reformatting the label feature to understand bias
85
- labels_list = prototyping_dataset['label']
86
  df_labels = pd.Series(labels_list)
87
  label_count = df_labels.value_counts(sort=False)
88
 
@@ -111,6 +112,7 @@ clearml_logger.report_scalar(
111
  value=(max_count / min_count),
112
  iteration=1
113
  )
 
114
  print("--- Class imbalance analysis --- ")
115
  print(f"Max labels in a class: {max_count}")
116
  print(f"Min labels in a class: {min_count}")
@@ -122,16 +124,17 @@ class_names = features['label'].names
122
  formatted_class_names = [" ".join(name.replace('_', ' ').split()) for name in class_names]
123
  label_count.index = formatted_class_names
124
 
 
125
  plt.figure(figsize=(10,6))
126
  label_count.plot(kind='bar', color='skyblue')
127
- plt.title("Class Distribution in Prototype Dataset")
128
  plt.xlabel("Class")
129
  plt.ylabel("Count")
130
  plt.tight_layout()
131
 
132
  clearml_logger.report_matplotlib_figure(
133
  title="EDA Class Distribution",
134
- series="Prototype Subset",
135
  figure=plt.gcf(),
136
  iteration=1
137
  )
@@ -149,7 +152,7 @@ if __name__ == "__main__":
149
  }
150
 
151
  prototype_loaders = make_dataset_loaders(
152
- prototyping_dataset, SEED, BATCH_SIZE, TEST_SIZE, aug_config
153
  )
154
 
155
  print("\n--- Handoff Test Successful ---")
@@ -173,14 +176,9 @@ if __name__ == "__main__":
173
  print(f"Validation loader batches: {len(final_loaders['val'])}")
174
  print(f"Test loader batches: {len(final_loaders['test'])}")
175
 
176
- # Record dataset info in ClearML
177
- task.connect_configuration(
178
- {"dataset_id": clearml_dataset.id},
179
- name="Dataset Metadata"
180
- )
181
- task.mark_completed()
182
 
183
-
184
  # Close the ClearML task
 
185
  task.close()
 
186
  print("\n--- Script Finished ---")
 
45
 
46
 
47
  # ----- ClearML Setup -----
48
+ project_name = "Small Group Project"
49
  task = Task.init(
50
+ project_name=f'{project_name}/Data Preparation',
51
  task_name='Data Preparation',
52
  task_type=Task.TaskTypes.data_processing
53
  )
 
75
  })
76
 
77
  # ----- Load a subset from a given dataset & track with ClearML -----
78
+ data_plants, subset_dataset, features = make_subset(
79
+ DATASET_LINK, DATASET_SUBSET_RATIO, task
80
  )
81
 
82
 
83
  # ---- Exploratory data analysis (EDA) ----
84
 
85
  # Reformatting the label feature to understand bias
86
+ labels_list = subset_dataset['label']
87
  df_labels = pd.Series(labels_list)
88
  label_count = df_labels.value_counts(sort=False)
89
 
 
112
  value=(max_count / min_count),
113
  iteration=1
114
  )
115
+
116
  print("--- Class imbalance analysis --- ")
117
  print(f"Max labels in a class: {max_count}")
118
  print(f"Min labels in a class: {min_count}")
 
124
  formatted_class_names = [" ".join(name.replace('_', ' ').split()) for name in class_names]
125
  label_count.index = formatted_class_names
126
 
127
+ # Plotting class distribution
128
  plt.figure(figsize=(10,6))
129
  label_count.plot(kind='bar', color='skyblue')
130
+ plt.title("Class Distribution in Subset Dataset")
131
  plt.xlabel("Class")
132
  plt.ylabel("Count")
133
  plt.tight_layout()
134
 
135
  clearml_logger.report_matplotlib_figure(
136
  title="EDA Class Distribution",
137
+ series="Subset Dataset",
138
  figure=plt.gcf(),
139
  iteration=1
140
  )
 
152
  }
153
 
154
  prototype_loaders = make_dataset_loaders(
155
+ subset_dataset, SEED, BATCH_SIZE, TEST_SIZE, aug_config
156
  )
157
 
158
  print("\n--- Handoff Test Successful ---")
 
176
  print(f"Validation loader batches: {len(final_loaders['val'])}")
177
  print(f"Test loader batches: {len(final_loaders['test'])}")
178
 
 
 
 
 
 
 
179
 
 
180
  # Close the ClearML task
181
+ task.mark_completed()
182
  task.close()
183
+
184
  print("\n--- Script Finished ---")
dataPrep/helpers/clearml_data.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+
4
+ from clearml import Task, Dataset
5
+ from datasets import load_dataset
6
+ from dataPrep.helpers.transforms_loaders import make_dataset_loaders
7
+
8
+
9
+ '''
10
+ Takes latest Data Prep ClearML task from project and reconstruct:
11
+ - data loaders for both full and subset datasets
12
+ - Aug settings used
13
+ '''
14
+ def extract_latest_data_task(project_name: str = "Small Group Project", num_workers: int = 8):
15
+
16
+ # --------- Get latest Data Preparation task from ClearML ---------
17
+
18
+ all_tasks = Task.get_tasks(
19
+ project_name=f'{project_name}/Data Preparation',
20
+ allow_archived=False,
21
+ task_filter={'order_by': ["-last_update"]},
22
+ )
23
+
24
+ if not all_tasks:
25
+ raise RuntimeError(f"No tasks found in project '{project_name}'")
26
+
27
+ dp_tasks = [
28
+ t for t in all_tasks
29
+ if t.task_type == Task.TaskTypes.data_processing
30
+ and t.completed is not None
31
+ ]
32
+
33
+ if not dp_tasks:
34
+ raise RuntimeError("No 'Data Preparation' tasks found in this project!")
35
+
36
+ # Latest Data Prep Task
37
+ latest_task = dp_tasks[0]
38
+ DYNAMIC_TASK_ID = latest_task.id
39
+ DATA_PREP = Task.get_task(task_id=DYNAMIC_TASK_ID)
40
+
41
+ # Load subset indices artifact from Data Prep task
42
+ artifacts = DATA_PREP.artifacts
43
+ if "subset_indices" not in artifacts:
44
+ raise RuntimeError("Data Prep task did not upload 'subset_indices' artifact!")
45
+
46
+ artifact = artifacts["subset_indices"]
47
+ subset_indices_path = artifact.get_local_copy()
48
+ subset_indices = np.load(subset_indices_path)
49
+
50
+ # Load dataset metadata from Data Prep task
51
+ data_params = DATA_PREP.get_parameters()
52
+
53
+ subset_ratio = float(data_params['General/dataset/subset_ratio'])
54
+ dataset_link = data_params['General/dataset/link']
55
+ seed = int(data_params['General/seed'])
56
+ batch_size = int(data_params['General/dataloaders/batch_size'])
57
+ test_size = float(data_params['General/dataloaders/test_size'])
58
+
59
+ aug_config = {
60
+ 'rotation': float(data_params['General/augmentation/rotation']),
61
+ 'brightness': float(data_params['General/augmentation/brightness']),
62
+ 'saturation': float(data_params['General/augmentation/saturation']),
63
+ 'blur': float(data_params['General/augmentation/blur']),
64
+ }
65
+
66
+
67
+ # Load Full Dataset
68
+ try:
69
+ ds = load_dataset(dataset_link)
70
+ except Exception as e:
71
+ raise RuntimeError(f"Error loading the dataset: {e}")
72
+
73
+ full_dataset = ds['train']
74
+
75
+ # Apply subset indices to full dataset - this gives you the same subset as data prep
76
+ subset_dataset = full_dataset.select(subset_indices)
77
+
78
+ # Get data loaders for both full and subset datasets
79
+ subset_loaders, full_loaders, aug_config = get_data_loaders(data_params, subset_dataset, full_dataset, num_workers=num_workers)
80
+ batch_size = int(data_params['General/dataloaders/batch_size'])
81
+ seed = int(data_params['General/seed'])
82
+
83
+
84
+ # Gather data prep task metadata
85
+ data_prep_metadata = {
86
+ "data_prep_task_id": DYNAMIC_TASK_ID,
87
+ "dataset_link": dataset_link,
88
+ "subset_ratio_used": subset_ratio,
89
+ "augmentation_used": aug_config,
90
+ "batch_size_used": batch_size,
91
+ "seed_used": seed,
92
+ "test_size_used": test_size
93
+ }
94
+
95
+ return subset_loaders, full_loaders, data_prep_metadata
96
+
97
+
98
+ '''
99
+ Takes a given dataset, subset, data params to create DataLoaders
100
+ Loaders split data into train, val, test
101
+ '''
102
+ def get_data_loaders(data_params, subset_dataset, full_dataset, num_workers):
103
+
104
+ # Extract data parameters- these will be used in the DataLoaders
105
+ seed = int(data_params['General/seed'])
106
+ batch_size = int(data_params['General/dataloaders/batch_size'])
107
+ test_size = float(data_params['General/dataloaders/test_size'])
108
+
109
+ aug_config = {
110
+ 'rotation': float(data_params['General/augmentation/rotation']),
111
+ 'brightness': float(data_params['General/augmentation/brightness']),
112
+ 'saturation': float(data_params['General/augmentation/saturation']),
113
+ 'blur': float(data_params['General/augmentation/blur'])
114
+ }
115
+
116
+ # Create DataLoaders using the parameters from data prep
117
+ subset_loaders = make_dataset_loaders(
118
+ subset_dataset, seed, batch_size, test_size, aug_config, workers=num_workers
119
+ )
120
+
121
+ print("\n--- Handoff Test Successful ---")
122
+ print(f"Prototype Train loader batches: {len(subset_loaders['train'])}")
123
+ print(f"Prototype Validation loader batches: {len(subset_loaders['val'])}")
124
+ print(f"Prototype Test loader batches: {len(subset_loaders['test'])}")
125
+
126
+
127
+ full_loaders = make_dataset_loaders(
128
+ full_dataset, seed, batch_size, test_size, aug_config, workers=num_workers
129
+ )
130
+
131
+ print("\n--- Handoff Test Successful ---")
132
+ print(f"Train loader batches: {len(full_loaders['train'])}")
133
+ print(f"Validation loader batches: {len(full_loaders['val'])}")
134
+ print(f"Test loader batches: {len(full_loaders['test'])}")
135
+
136
+ return subset_loaders, full_loaders, aug_config
dataPrep/helpers/create_dataset.py CHANGED
@@ -6,7 +6,6 @@ import os
6
  import random
7
  import numpy as np
8
  from datasets import load_dataset
9
- from clearml import Dataset
10
 
11
 
12
  '''
@@ -14,7 +13,7 @@ Load a DS from HuggingFace Link & randomly subset it - upload subset to ClearML
14
  Subset indicies are uploaded to ClearML for reproducibility
15
  REPRODUCE: Load full DS, then load indicies from ClearML to get same subset
16
  '''
17
- def make_subset(dataset_link, subset_ratio, clearml_logger):
18
 
19
  # Load dataset
20
  try:
@@ -34,36 +33,16 @@ def make_subset(dataset_link, subset_ratio, clearml_logger):
34
  random.shuffle(indices)
35
  subset_indices = indices[:subset_size]
36
 
37
- prototyping_dataset = data_plants.select(subset_indices)
38
- # I THINK WE NEED TO REMOVE THIS LATER
39
- # We dont really need to upload subset everytime (Im not sure tho)
40
- # Register subset in ClearML
41
- clearml_dataset = Dataset.create(
42
- dataset_name="Plant Village Prototype",
43
- dataset_project="Small Group Project",
44
- dataset_tags=["prototype", "subset"],
45
- use_current_task=False
46
- )
47
- clearml_dataset.add_tags([
48
- f"subset_ratio_{subset_ratio}",
49
- "hf_source"
50
- ])
51
 
52
- # Save indices
53
  subset_path = "subset_indices.npy"
54
  np.save(subset_path, subset_indices)
55
- clearml_dataset.add_files(subset_path)
56
- clearml_dataset.set_metadata({
57
- "huggingface_dataset": dataset_link,
58
- "subset_ratio": subset_ratio,
59
- "total_samples": len(prototyping_dataset)
60
- })
61
-
62
- clearml_dataset.upload()
63
- clearml_dataset.finalize()
64
- clearml_logger.report_text(f"Created ClearML Dataset: {clearml_dataset.id}")
65
 
66
- # Clean up local file
67
- os.remove(subset_path)
 
 
 
68
 
69
- return data_plants, prototyping_dataset, features, clearml_dataset
 
6
  import random
7
  import numpy as np
8
  from datasets import load_dataset
 
9
 
10
 
11
  '''
 
13
  Subset indicies are uploaded to ClearML for reproducibility
14
  REPRODUCE: Load full DS, then load indicies from ClearML to get same subset
15
  '''
16
+ def make_subset(dataset_link, subset_ratio, clearml_task):
17
 
18
  # Load dataset
19
  try:
 
33
  random.shuffle(indices)
34
  subset_indices = indices[:subset_size]
35
 
36
+ subset_dataset = data_plants.select(subset_indices)
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
+ # -------- Upload the subset indices as a ClearML artifact --------
39
  subset_path = "subset_indices.npy"
40
  np.save(subset_path, subset_indices)
 
 
 
 
 
 
 
 
 
 
41
 
42
+ clearml_task.upload_artifact(
43
+ name="subset_indices",
44
+ artifact_object=subset_path
45
+ )
46
+ clearml_task.get_logger().report_text(f"Uploaded subset indices as artifact: {subset_path}")
47
 
48
+ return data_plants, subset_dataset, features
dataPrep/helpers/transforms_loaders.py CHANGED
@@ -47,24 +47,25 @@ def make_augment_pipeline(aug_config):
47
  return augmentation
48
 
49
 
 
 
 
 
 
 
 
 
 
50
  """
51
  Creates and returns DataLoaders (train, val, test) for a given dataset.
52
  Performs a 70/15/15 split
53
  """
54
- def make_dataset_loaders(dataset, seed, batch_size, test_size, aug_config):
55
 
56
  # Define transformation pipelines for the dataset
57
  normalisation = make_norm_pipeline()
58
  augmentation = make_augment_pipeline(aug_config)
59
 
60
- def apply_augmentation(batch):
61
- batch['image'] = [augmentation(x) for x in batch['image']]
62
- return batch
63
-
64
- def apply_normalisation(batch):
65
- batch['image'] = [normalisation(x) for x in batch['image']]
66
- return batch
67
-
68
  # 70/30 split creates train set
69
  split_1 = dataset.train_test_split(test_size=test_size, seed=seed)
70
  train_split = split_1['train']
@@ -76,14 +77,34 @@ def make_dataset_loaders(dataset, seed, batch_size, test_size, aug_config):
76
  val_split, test_split = split_2['train'], split_2['test']
77
 
78
  # Put each split through pipelines
79
- train_split.set_transform(apply_augmentation)
80
- val_split.set_transform(apply_normalisation)
81
- test_split.set_transform(apply_normalisation)
82
 
83
  # Create dataloader for each
84
- train_loader = DataLoader(train_split, batch_size=batch_size, shuffle=True)
85
- val_loader = DataLoader(val_split, batch_size=batch_size, shuffle=False)
86
- test_loader = DataLoader(test_split, batch_size=batch_size, shuffle=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  dataset_loaders = {
89
  "train": train_loader,
 
47
  return augmentation
48
 
49
 
50
+ def apply_augmentation(batch, augmentation):
51
+ batch['image'] = [augmentation(x) for x in batch['image']]
52
+ return batch
53
+
54
+ def apply_normalisation(batch, normalisation):
55
+ batch['image'] = [normalisation(x) for x in batch['image']]
56
+ return batch
57
+
58
+
59
  """
60
  Creates and returns DataLoaders (train, val, test) for a given dataset.
61
  Performs a 70/15/15 split
62
  """
63
+ def make_dataset_loaders(dataset, seed, batch_size, test_size, aug_config, workers=8):
64
 
65
  # Define transformation pipelines for the dataset
66
  normalisation = make_norm_pipeline()
67
  augmentation = make_augment_pipeline(aug_config)
68
 
 
 
 
 
 
 
 
 
69
  # 70/30 split creates train set
70
  split_1 = dataset.train_test_split(test_size=test_size, seed=seed)
71
  train_split = split_1['train']
 
77
  val_split, test_split = split_2['train'], split_2['test']
78
 
79
  # Put each split through pipelines
80
+ train_split.set_transform(lambda batch: apply_augmentation(batch, augmentation))
81
+ val_split.set_transform(lambda batch: apply_normalisation(batch, normalisation))
82
+ test_split.set_transform(lambda batch: apply_normalisation(batch, normalisation))
83
 
84
  # Create dataloader for each
85
+ train_loader = DataLoader(
86
+ train_split,
87
+ batch_size=batch_size,
88
+ shuffle=True,
89
+ pin_memory=True,
90
+ num_workers=workers
91
+ )
92
+ val_loader = DataLoader(
93
+ val_split,
94
+ batch_size=batch_size,
95
+ shuffle=False,
96
+ pin_memory=True,
97
+ num_workers=workers
98
+ )
99
+ test_loader = DataLoader(
100
+ test_split,
101
+ batch_size=batch_size,
102
+ shuffle=False,
103
+ pin_memory=True,
104
+ num_workers=workers
105
+ )
106
+
107
+ print(f"\nWorkers used in DataLoaders: {workers}\n")
108
 
109
  dataset_loaders = {
110
  "train": train_loader,
requirements.txt CHANGED
@@ -1,29 +1,19 @@
1
 
2
  # Core dependencies
3
- torch>=2.0.0
4
- torchvision>=0.15.0
5
- gradio>=4.0.0
6
- numpy>=1.24.0
7
- Pillow>=10.0.0
 
8
 
9
- # For model deployment and tracking
10
- huggingface-hub>=0.19.0
11
- clearml>=1.14.0
12
-
13
- # Optional: for advanced features
14
- datasets>=2.14.0 # For loading PlantVillage dataset from HuggingFace
15
- # -- Data prep requirements --
16
  # Data Handling & Analysis
17
- numpy
18
- pandas
19
- datasets
20
 
21
  # Visualization
22
- matplotlib
23
 
24
- # PyTorch (Machine Learning)
25
- torch
26
- torchvision
27
-
28
- # Experiment Tracking
29
- clearml
 
1
 
2
  # Core dependencies
3
+ torch==2.2.2
4
+ torchvision==0.17.2
5
+ torcheval==0.0.7
6
+ numpy==1.26.4
7
+ Pillow==10.3.0
8
+ gradio==4.19.0
9
 
 
 
 
 
 
 
 
10
  # Data Handling & Analysis
11
+ pandas==2.2.2
12
+ datasets==2.18.0
 
13
 
14
  # Visualization
15
+ matplotlib==3.8.4
16
 
17
+ # For model deployment and tracking
18
+ huggingface-hub==0.23.0
19
+ clearml==2.0.2
 
 
 
testingModel/helpers/evaluation.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.nn import CrossEntropyLoss
3
+
4
+
5
+ """
6
+ Evaluates a trained model on a dataloader that returns batches like:
7
+ batch["image"] -> Tensor [B, 3, 256, 256]
8
+ batch["label"] -> Tensor [B]
9
+
10
+ Returns dict:
11
+ { "accuracy": float, "loss": float }
12
+ """
13
+ def make_predictions(model, dataloader, device):
14
+
15
+ model.eval()
16
+ criterion = CrossEntropyLoss()
17
+
18
+ total_loss = 0
19
+ total_correct = 0
20
+ total_samples = 0
21
+
22
+ with torch.no_grad():
23
+ for batch in dataloader:
24
+
25
+ # Move tensors to device
26
+ images = batch["image"].to(device)
27
+ labels = batch["label"].to(device).long()
28
+
29
+ # Forward pass
30
+ outputs = model(images)
31
+ loss = criterion(outputs, labels)
32
+
33
+ total_loss += loss.item() * images.size(0)
34
+ total_correct += (outputs.argmax(dim=1) == labels).sum().item()
35
+ total_samples += labels.size(0)
36
+
37
+ accuracy = total_correct / total_samples
38
+ avg_loss = total_loss / total_samples
39
+
40
+ return {
41
+ "accuracy": accuracy,
42
+ "loss": avg_loss,
43
+ }
testingModel/run_testing.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from clearml import Task
2
+ from dataPrep.helpers.clearml_data import extract_latest_data_task
3
+
4
+ import torch
5
+ from models.modelOne import modelOne
6
+ from testingModel.helpers.evaluation import make_predictions
7
+
8
+
9
+ # -------------- Load Data --------------
10
+ project_name = "Small Group Project"
11
+ subset_loaders, full_loaders, data_prep_metadata = extract_latest_data_task(project_name=project_name)
12
+
13
+
14
+ # -------- ClearML Testing Task Setup --------
15
+ testing_task = Task.init(
16
+ project_name=f"{project_name}/Model Testing",
17
+ task_name="Model Testing",
18
+ task_type=Task.TaskTypes.testing,
19
+ reuse_last_task_id=False,
20
+ )
21
+
22
+ # Reference the data prep task used
23
+ testing_logger = testing_task.get_logger()
24
+ testing_task.connect(data_prep_metadata, name="data_prep_metadata_READONLY")
25
+
26
+ CLEARML_TRAINING_ID = "5bac154a885b4acbaa07d8588027bb27"
27
+
28
+ # Testing parameters - Modify these when experimenting
29
+ testing_config = {
30
+ "model_train_id": CLEARML_TRAINING_ID,
31
+ "num_classes": 39,
32
+ "model_path": "best_model.pt",
33
+ }
34
+ testing_task.connect(testing_config)
35
+
36
+ # Load the model weights from ClearML training task
37
+ training_task = Task.get_task(task_id=testing_config["model_train_id"])
38
+ model_artifact = training_task.artifacts.get("best_model")
39
+ model_path = model_artifact.get_local_copy()
40
+
41
+ # Reference training metadata
42
+ training_hyperparams = training_task.get_parameters_as_dict()
43
+ testing_task.connect(training_hyperparams['General'], name="training_metadata_READONLY")
44
+
45
+
46
+ # -------- Rebuild the ML model --------
47
+ model = modelOne()
48
+ state_dict = torch.load(model_path, map_location="cpu") # Load to CPU first
49
+ model.load_state_dict(state_dict)
50
+ model.eval() # set dropout & batch norm layers to eval mode
51
+
52
+ # Move model to GPU if available
53
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
54
+ model.to(device)
55
+
56
+
57
+ # -------------------- Test model on test set --------------------
58
+ testing_logger.report_text("Starting evaluation on TEST SUBSET...\n")
59
+ test_subset = subset_loaders['test']
60
+
61
+ subset_results = make_predictions(model, test_subset, device)
62
+
63
+
64
+ # Accuracy & Loss logging
65
+ testing_logger.report_single_value(name="Test Subset Accuracy", value=subset_results["accuracy"])
66
+ testing_logger.report_single_value(name="Test Subset Loss", value=subset_results["loss"])
67
+
68
+
69
+ # --------- Complete -----------------
70
+ print("\n------ Testing Complete ------")
71
+ testing_logger.report_text(
72
+ f"TEST SUBSET RESULTS:\n"
73
+ f"Loss: {subset_results['loss']:.4f}\n"
74
+ f"Accuracy: {subset_results['accuracy']:.4f}\n"
75
+ )
76
+ testing_task.close()
trainingModel/Training.py DELETED
@@ -1,150 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- import numpy as np
4
- from torcheval.metrics import MulticlassAccuracy
5
- from torch.utils.data import DataLoader
6
-
7
-
8
- # fix errors in runtime
9
-
10
-
11
- def train_model(
12
- model: nn.Module,
13
- train_loader: DataLoader,
14
- val_loader: DataLoader,
15
- device: torch.device,
16
- n_epochs: int = 4,
17
- lr: float = 1e-3,
18
- save_path: str = "best_model.pt",
19
- flatten_input = False,
20
- num_classes : int = 39,
21
-
22
- ):
23
- """
24
- Trains the given model and returns:
25
- - training_losses: numpy array of loss per batch
26
- - training_accuracies: numpy array of running accuracy per batch
27
- - val_accuracies: numpy array of accuracy per epoch
28
- - best_accuracy: highest validation accuracy achieved
29
-
30
- Expected batch format:
31
- batch["image"] → Tensor [B, C, H, W]
32
- batch["label"] → Tensor [B] with class IDs (int64)
33
- Model output:
34
- outputs → Tensor [B, num_classes] (logits)
35
- """
36
-
37
-
38
- # Move model to device
39
- model.to(device)
40
-
41
- # Loss and optimizer
42
- criterion = nn.CrossEntropyLoss()
43
- optimizer = torch.optim.Adam(model.parameters(), lr=lr ) # might add momentum 0.9 later
44
-
45
- # Metric trackers
46
- train_accuracy_fn = MulticlassAccuracy(num_classes=num_classes)
47
- val_accuracy_fn = MulticlassAccuracy(num_classes=num_classes)
48
-
49
- # Arrays to log metrics
50
- num_batches = len(train_loader)
51
-
52
- if num_batches == 0:
53
- raise RuntimeError("UH OH!!!! empty train loader")
54
-
55
- # Store training losses and accuracies for every batch
56
- # num_batches is the number of batches for every epoch
57
- training_losses = np.zeros(num_batches * n_epochs)
58
- training_accuracies = np.zeros(num_batches * n_epochs)
59
-
60
- # store validation accuracy for every epoch
61
- val_accuracies = np.zeros(n_epochs)
62
-
63
- # keep track of best validation accuracy and best model
64
- best_accuracy = 0.0
65
-
66
- #----------------------
67
- # training loop
68
- #----------------------
69
-
70
- for epoch in range(n_epochs):
71
- model.train()
72
- train_accuracy_fn.reset()
73
-
74
- # iterate over all the dataloader's mini-batches
75
- for i, batch in enumerate(train_loader):
76
-
77
- # move to GPU memory
78
- inputs = batch["image"].to(device)
79
- labels = batch["label"].to(device).long()
80
-
81
- # flatten if not cnn REVISE LATER
82
- if flatten_input:
83
- inputs = inputs.view(inputs.size(0), -1)
84
-
85
- optimizer.zero_grad()
86
-
87
- # Forward pass
88
- outputs = model(inputs)
89
- loss = criterion(outputs, labels)
90
-
91
- # Backward pass
92
- loss.backward()
93
-
94
- # updates the parameters
95
- optimizer.step()
96
-
97
- # log the loss value
98
- training_losses[epoch * num_batches + i] = loss.item()
99
-
100
- #updates the accuracy computation with new data
101
- train_accuracy_fn.update(outputs, labels)
102
-
103
- #compute accuracy with the current data
104
- training_accuracies[epoch * num_batches + i] = train_accuracy_fn.compute().item()
105
-
106
- print(f'Epoch {epoch + 1} training complete')
107
-
108
- # ----------------------
109
- # validation loop
110
- # ----------------------
111
-
112
- model.eval()
113
- val_accuracy_fn.reset()
114
-
115
-
116
- with torch.no_grad():
117
- for batch in val_loader:
118
- inputs = batch["image"].to(device)
119
- labels = batch["label"].to(device).long()
120
-
121
- # flatten if not cnn REVISE LATER
122
- if flatten_input:
123
- inputs = inputs.view(inputs.size(0), -1)
124
-
125
- outputs = model(inputs)
126
-
127
- val_accuracy_fn.update(outputs, labels)
128
-
129
- current_accuracy = val_accuracy_fn.compute().item()
130
- val_accuracies[epoch] = current_accuracy
131
-
132
- # keep track of best validation accuracy and save best model so far
133
- if current_accuracy > best_accuracy:
134
- best_accuracy = current_accuracy
135
- torch.save(model.state_dict(), save_path)
136
- print(f'Epoch {epoch + 1} (validation accuracy: {best_accuracy})')
137
- print(f'Epoch {epoch + 1} validation complete')
138
-
139
- print(f"\nTraining finished. Best val accuracy: {best_accuracy:.4f}")
140
- print(f"Best model weights saved to: {save_path}")
141
-
142
- training_metrics = {
143
- "losses": training_losses,
144
- "accuracies": training_accuracies,
145
- "val_accuracies": val_accuracies,
146
- "best_accuracy": best_accuracy,
147
- }
148
-
149
- return training_metrics
150
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
trainingModel/helpers/Training.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import numpy as np
4
+ from torcheval.metrics import MulticlassAccuracy
5
+ from torch.utils.data import DataLoader
6
+
7
+
8
+
9
+
10
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+ print("Using device:", DEVICE)
12
+
13
+ def train_model(
14
+ model: nn.Module,
15
+ train_loader: DataLoader,
16
+ val_loader: DataLoader,
17
+ n_epochs: int = 4,
18
+ lr: float = 1e-3,
19
+ save_path: str = "best_model.pt",
20
+ num_classes : int = 39,
21
+ early_stop : int = 3,
22
+
23
+
24
+ ):
25
+ """
26
+ Trains the given model and returns:
27
+ - training_losses: numpy array of loss per epoch
28
+ - training_accuracies: numpy array of running accuracy per epoch
29
+ - val_accuracies: numpy array of accuracy per epoch
30
+ - best_accuracy: highest validation accuracy achieved
31
+
32
+
33
+ Expected batch format:
34
+ batch["image"] → Tensor [B, C, H, W]
35
+ batch["label"] → Tensor [B] with class IDs (int64)
36
+ Model output:
37
+ outputs → Tensor [B, num_classes] (logits)
38
+ """
39
+
40
+
41
+ # Move model to device
42
+ model.to(DEVICE)
43
+
44
+
45
+ # Loss and optimizer
46
+ criterion = nn.CrossEntropyLoss()
47
+ optimizer = torch.optim.Adam(model.parameters(), lr=lr ) # might add momentum 0.9 later
48
+
49
+
50
+ # Metric trackers
51
+ train_accuracy_fn = MulticlassAccuracy(num_classes=num_classes)
52
+ val_accuracy_fn = MulticlassAccuracy(num_classes=num_classes)
53
+
54
+
55
+ # Arrays to log metrics
56
+ num_batches = len(train_loader)
57
+
58
+
59
+ if num_batches == 0:
60
+ raise RuntimeError("UH OH!!!! empty train loader")
61
+
62
+
63
+ # Store training losses and accuracies for every epoch
64
+ training_losses = np.zeros(n_epochs)
65
+ training_accuracies = np.zeros(n_epochs)
66
+
67
+
68
+ # store validation accuracy for every epoch
69
+ val_accuracies = np.zeros(n_epochs)
70
+
71
+
72
+ # keep track of best validation accuracy and best model
73
+ best_accuracy = 0.0
74
+
75
+
76
+ # keep track of accuracy improvement
77
+ improv_counter = 0
78
+
79
+
80
+ #----------------------
81
+ # training loop
82
+ #----------------------
83
+
84
+ for epoch in range(n_epochs):
85
+ model.train()
86
+ train_accuracy_fn.reset()
87
+
88
+
89
+ training_loss = 0.0
90
+
91
+
92
+ # iterate over all the dataloader's mini-batches
93
+ for i, batch in enumerate(train_loader):
94
+
95
+
96
+ # move to GPU memory
97
+ inputs = batch["image"].to(DEVICE)
98
+ labels = batch["label"].to(DEVICE).long()
99
+
100
+
101
+
102
+
103
+ optimizer.zero_grad()
104
+
105
+
106
+ # Forward pass
107
+ outputs = model(inputs)
108
+ loss = criterion(outputs, labels)
109
+
110
+ # Backward pass
111
+ loss.backward()
112
+
113
+
114
+ # updates the parameters
115
+ optimizer.step()
116
+
117
+ # log the loss value for epoch
118
+ training_loss += loss.item()
119
+
120
+
121
+ #updates the accuracy computation with new data
122
+ train_accuracy_fn.update(outputs, labels)
123
+
124
+
125
+ # compute epoch-level training metrics
126
+ training_losses[epoch] = training_loss / num_batches
127
+ training_accuracies[epoch] = train_accuracy_fn.compute().item()
128
+
129
+
130
+ print(f'Epoch {epoch + 1} training complete. Training Accuracy: {training_accuracies[epoch]:.4f}')
131
+
132
+
133
+ # ----------------------
134
+ # validation loop
135
+ # ----------------------
136
+
137
+
138
+ model.eval()
139
+ val_accuracy_fn.reset()
140
+
141
+
142
+
143
+
144
+ with torch.no_grad():
145
+ for batch in val_loader:
146
+ inputs = batch["image"].to(DEVICE)
147
+ labels = batch["label"].to(DEVICE).long()
148
+
149
+
150
+ outputs = model(inputs)
151
+
152
+
153
+ val_accuracy_fn.update(outputs, labels)
154
+
155
+
156
+ current_accuracy = val_accuracy_fn.compute().item()
157
+ val_accuracies[epoch] = current_accuracy
158
+
159
+
160
+ # keep track of best validation accuracy and save best model so far
161
+ if current_accuracy > best_accuracy:
162
+ best_accuracy = current_accuracy
163
+ torch.save(model.state_dict(), save_path)
164
+ improv_counter = 0 #Resets coounter if accuracy improves
165
+ print(f'Epoch {epoch + 1} (validation accuracy: {best_accuracy})')
166
+
167
+
168
+ else:
169
+ improv_counter +=1
170
+ print(f'No improvement for {improv_counter} epoch')
171
+
172
+
173
+ if improv_counter >= early_stop:
174
+ print (f"Early stopping at epoch {epoch +1}")
175
+ break
176
+
177
+
178
+
179
+
180
+ print(f'Epoch {epoch + 1} validation complete')
181
+
182
+
183
+ print(f"\nTraining finished. Best val accuracy: {best_accuracy:.4f}")
184
+ print(f"Best model weights saved to: {save_path}")
185
+
186
+
187
+ training_metrics = {
188
+ "losses": training_losses,
189
+ "accuracies": training_accuracies,
190
+ "val_accuracies": val_accuracies,
191
+ "best_accuracy": best_accuracy
192
+
193
+ }
194
+
195
+ return training_metrics
196
+
197
+
198
+
199
+
trainingModel/run_training.py CHANGED
@@ -1,124 +1,37 @@
1
  import os
2
- import numpy as np
3
- from clearml import Task, Dataset
4
- from datasets import load_dataset
5
 
6
- # Latest Data Prep Task
7
- all_tasks = Task.get_tasks(project_name="Small Group Project")
8
- if not all_tasks:
9
- raise RuntimeError("No tasks found in project 'Small Group Project'")
10
 
11
- dp_tasks = [t for t in all_tasks if t.name == "Data Preparation"]
12
- if not dp_tasks:
13
- raise RuntimeError("No 'Data Preparation' tasks found in this project!")
14
 
15
- <<<<<<< HEAD
16
  # -------------- Load Data --------------
17
-
18
- all_tasks = Task.get_tasks(project_name="Small Group Project")
19
- if not all_tasks:
20
- raise RuntimeError("No tasks found in project 'Small Group Project'")
21
-
22
- dp_tasks = [t for t in all_tasks if t.name == "Data Preparation"]
23
- if not dp_tasks:
24
- raise RuntimeError("No 'Data Preparation' tasks found in this project!")
25
-
26
- # Latest Data Prep Task
27
- latest_task = max(dp_tasks, key=lambda t: t.id)
28
- DYNAMIC_TASK_ID = latest_task.id
29
- DATA_PREP = Task.get_task(task_id=DYNAMIC_TASK_ID)
30
-
31
- =======
32
- latest_task = max(dp_tasks, key=lambda t: t.id)
33
- DYNAMIC_TASK_ID = latest_task.id
34
- DATA_PREP = Task.get_task(task_id=DYNAMIC_TASK_ID)
35
-
36
- >>>>>>> 20050ad82ebca27a376e15837a7abf79fca23e98
37
- # Dataset ID
38
- config_objects = DATA_PREP.get_configuration_objects()
39
- raw_meta = config_objects["Dataset Metadata"]
40
- dataset_id = raw_meta.split("=")[1].strip().replace('"', "")
41
-
42
- # Load ClearML Dataset
43
- subset_clearml = Dataset.get(dataset_id=dataset_id)
44
- local_folder = subset_clearml.get_local_copy()
45
-
46
- <<<<<<< HEAD
47
- subset_indices = np.load(os.path.join(local_folder, "subset_indices.npy"))
48
- =======
49
- subset_indices_path = os.path.join(local_folder, "subset_indices.npy")
50
- subset_indices = np.load(subset_indices_path)
51
- >>>>>>> 20050ad82ebca27a376e15837a7abf79fca23e98
52
-
53
- # Load Dataset Parameters
54
- data_params = DATA_PREP.get_parameters()
55
- dataset_link = data_params['General/dataset/link']
56
-
57
- # Load Full Dataset
58
- try:
59
- ds = load_dataset(dataset_link)
60
- except Exception as e:
61
- raise RuntimeError(f"Error loading the dataset: {e}")
62
-
63
- full_dataset = ds['train']
64
-
65
-
66
-
67
- # Apply subset indices to full dataset - this gives you the same subset as data prep
68
- subset_dataset = full_dataset.select(subset_indices)
69
-
70
-
71
- # Extract parameters from data prep task - these will create the DataLoaders
72
- seed = int(data_params['General/seed'])
73
- batch_size = int(data_params['General/dataloaders/batch_size'])
74
- test_size = float(data_params['General/dataloaders/test_size'])
75
-
76
- aug_config = {
77
- 'rotation': float(data_params['General/augmentation/rotation']),
78
- 'brightness': float(data_params['General/augmentation/brightness']),
79
- 'saturation': float(data_params['General/augmentation/saturation']),
80
- 'blur': float(data_params['General/augmentation/blur'])
81
- }
82
-
83
- # Create DataLoaders using the parameters from data prep
84
- subset_loaders = make_dataset_loaders(
85
- subset_dataset, seed, batch_size, test_size, aug_config
86
- )
87
-
88
- print("\n--- Handoff Test Successful ---")
89
- print(f"Prototype Train loader batches: {len(subset_loaders['train'])}")
90
- print(f"Prototype Validation loader batches: {len(subset_loaders['val'])}")
91
- print(f"Prototype Test loader batches: {len(subset_loaders['test'])}")
92
-
93
-
94
- full_loaders = make_dataset_loaders(
95
- full_dataset, seed, batch_size, test_size, aug_config
96
- )
97
-
98
- print("\n--- Handoff Test Successful ---")
99
- print(f"Train loader batches: {len(full_loaders['train'])}")
100
- print(f"Validation loader batches: {len(full_loaders['val'])}")
101
- print(f"Test loader batches: {len(full_loaders['test'])}")
102
- # -------------- DATA PREP ENDS --------------
103
 
104
 
105
  # -------- ClearML Training Task Setup --------
106
  training_task = Task.init(
107
- project_name="Small Group Project",
108
  task_name="Model Training",
109
  reuse_last_task_id=False,
110
  )
111
 
 
112
  training_logger = training_task.get_logger()
113
- training_task.connect({"data_prep_task_used": DYNAMIC_TASK_ID})
114
 
115
  # Training parameters - Modify these to experiment
116
  training_config = {
117
  "num_classes": 39,
118
  "n_epochs": 1,
119
  "learning_rate": 1e-3,
120
- "batch_size": batch_size,
121
  "save_path": "best_model.pt",
 
122
  }
123
  training_task.connect(training_config)
124
 
@@ -126,48 +39,45 @@ training_task.connect(training_config)
126
  # -------- Build the ML model --------
127
  model = modelOne(noOfClasses=training_config["num_classes"])
128
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
129
 
 
 
 
 
130
 
131
  # ------- Train the model (on subset for now) -------
132
 
133
- <<<<<<< HEAD
134
  print("\n--- Starting Model Training on Subset ---")
135
  training_metrics = train_model(
136
- =======
137
- #When calling this function, the model should be trained on the given dataset
138
-
139
- print("\n--- Starting Model Training on Subset ---")
140
- train_model(
141
- >>>>>>> 20050ad82ebca27a376e15837a7abf79fca23e98
142
  model=model,
143
  train_loader=subset_loaders['train'],
144
  val_loader=subset_loaders['val'],
145
- device=device,
146
  n_epochs=training_config["n_epochs"],
147
  lr=training_config["learning_rate"],
 
148
  save_path=training_config["save_path"],
 
149
  )
150
- <<<<<<< HEAD
151
 
152
 
153
  # ----------- Log metrics to ClearML -----------
154
- # Per-batch training losses and accuracies
155
- for i, loss in enumerate(training_metrics["losses"]):
156
- training_logger.report_scalar("train", "loss_per_batch", value=loss, iteration=i)
157
 
158
- for i, acc in enumerate(training_metrics["accuracies"]):
159
- training_logger.report_scalar("train", "accuracy_per_batch", value=acc, iteration=i)
160
 
161
- # Per-epoch validation accuracy
162
  for epoch, acc in enumerate(training_metrics["val_accuracies"]):
163
- training_logger.report_scalar("validation", "accuracy_per_epoch", value=acc, iteration=epoch)
164
 
 
165
  training_logger.report_single_value("best_val_accuracy", training_metrics["best_accuracy"])
166
 
167
  # Upload best model as artifact
168
  training_task.upload_artifact("best_model", training_config["save_path"])
169
 
170
  print("\nTraining complete.")
171
- training_task.close()
172
- =======
173
- >>>>>>> 20050ad82ebca27a376e15837a7abf79fca23e98
 
1
  import os
2
+ from clearml import Task
3
+ from dataPrep.helpers.clearml_data import extract_latest_data_task
 
4
 
5
+ import torch
6
+ from models.modelOne import modelOne
7
+ from trainingModel.helpers.Training import train_model
 
8
 
 
 
 
9
 
 
10
  # -------------- Load Data --------------
11
+ NUM_WORKERS = 0
12
+ project_name = "Small Group Project"
13
+ subset_loaders, full_loaders, data_prep_metadata = extract_latest_data_task(project_name=project_name, num_workers=NUM_WORKERS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
 
16
  # -------- ClearML Training Task Setup --------
17
  training_task = Task.init(
18
+ project_name=f"{project_name}/Model Training",
19
  task_name="Model Training",
20
  reuse_last_task_id=False,
21
  )
22
 
23
+ # Detail the data prep task used
24
  training_logger = training_task.get_logger()
25
+ training_task.connect(data_prep_metadata, name="data_prep_metadata_READONLY")
26
 
27
  # Training parameters - Modify these to experiment
28
  training_config = {
29
  "num_classes": 39,
30
  "n_epochs": 1,
31
  "learning_rate": 1e-3,
32
+ "optimizer": "adam",
33
  "save_path": "best_model.pt",
34
+ "num_workers": NUM_WORKERS
35
  }
36
  training_task.connect(training_config)
37
 
 
39
  # -------- Build the ML model --------
40
  model = modelOne(noOfClasses=training_config["num_classes"])
41
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
42
+ model.to(device)
43
 
44
+ # Print device info
45
+ print(f"\n**Using device: {device}**\n")
46
+ if device.type == 'cuda':
47
+ print(f"GPU Name: {torch.cuda.get_device_name(0)}")
48
 
49
  # ------- Train the model (on subset for now) -------
50
 
 
51
  print("\n--- Starting Model Training on Subset ---")
52
  training_metrics = train_model(
 
 
 
 
 
 
53
  model=model,
54
  train_loader=subset_loaders['train'],
55
  val_loader=subset_loaders['val'],
 
56
  n_epochs=training_config["n_epochs"],
57
  lr=training_config["learning_rate"],
58
+ num_classes=training_config["num_classes"],
59
  save_path=training_config["save_path"],
60
+ early_stop=3,
61
  )
 
62
 
63
 
64
  # ----------- Log metrics to ClearML -----------
65
+ # Per-epoch training losses and accuracies
66
+ for epoch, loss in enumerate(training_metrics["losses"]):
67
+ training_logger.report_scalar("training epoch loss", "loss", value=loss, iteration=epoch)
68
 
69
+ for epoch, acc in enumerate(training_metrics["accuracies"]):
70
+ training_logger.report_scalar("training epoch accuracy", "accuracy", value=acc, iteration=epoch)
71
 
72
+ # Per-epoch validation accuracies
73
  for epoch, acc in enumerate(training_metrics["val_accuracies"]):
74
+ training_logger.report_scalar("validation epoch accuracy", "accuracy", value=acc, iteration=epoch)
75
 
76
+ # Best validation accuracy
77
  training_logger.report_single_value("best_val_accuracy", training_metrics["best_accuracy"])
78
 
79
  # Upload best model as artifact
80
  training_task.upload_artifact("best_model", training_config["save_path"])
81
 
82
  print("\nTraining complete.")
83
+ training_task.close()
 
 
ui/app.py CHANGED
@@ -14,6 +14,10 @@ sys.path.append(str(Path(__file__).parent))
14
  sys.path.append(str(Path(__file__).parent.parent))
15
 
16
  from model_loader import ModelLoader
 
 
 
 
17
 
18
 
19
  class PlantDiseaseApp:
@@ -22,60 +26,98 @@ class PlantDiseaseApp:
22
  self.current_modelName = "CNN from Scratch"
23
  self.model = self.model_loader.loadModel(self.current_modelName)
24
  self.flagged_predictions = []
 
25
 
26
  def predict(self, image, modelName, confidence_threshold):
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  if image is None:
28
  return None, "Please upload an image", ""
29
 
30
  try:
 
31
  if modelName != self.current_modelName:
32
- self.model = self.model_loader.loadModel(modelName)
33
  self.current_modelName = modelName
34
 
35
  # Preprocess image
36
- tensor = preprocess_image(image)
37
- tensor = tensor.to(self.model_loader.device)
38
 
39
- # Get prediction
40
  with torch.no_grad():
41
  logits = self.model(tensor)
42
 
43
- # Postprocess
44
- top_predictions, all_predictions = postprocess_predictions(
45
- logits, config.CLASS_NAMES, config.TOP_K_PREDICTIONS
46
- )
 
47
 
48
  # Filter by confidence threshold
49
- filtered_predictions = {
50
- k: v for k, v in top_predictions.items() if v >= confidence_threshold / 100
51
- }
52
 
53
- # Get top prediction info
54
  if filtered_predictions:
55
  top_class = max(filtered_predictions.items(), key=lambda x: x[1])[0]
56
  top_prob = filtered_predictions[top_class]
57
  disease_info = get_disease_info(top_class)
58
 
59
  result_text = f"""
60
- **Top Prediction:** {disease_info['formatted_name']}
61
- **Confidence:** {top_prob*100:.2f}%
62
- **Plant:** {disease_info['plant']}
63
- **Status:** {'Healthy' if disease_info['is_healthy'] else 'Disease Detected'}
64
- """
65
  else:
66
  result_text = "No predictions above confidence threshold"
67
 
68
  # Format for Gradio Label component
69
- display_predictions = {
70
- format_class_name(k): v for k, v in filtered_predictions.items()
71
- }
72
 
73
- return display_predictions, result_text, json.dumps(filtered_predictions, indent=2)
 
 
 
 
74
 
75
  except Exception as e:
76
  return None, f"Error during prediction: {str(e)}", ""
77
 
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
  def create_interface():
81
  app = PlantDiseaseApp()
@@ -176,29 +218,6 @@ def create_interface():
176
  outputs=flag_output
177
  )
178
 
179
- with gr.Tab("Example Images"):
180
- gr.Markdown("### Try these example plant images")
181
- gr.Markdown("Click on an example below to load it into the predictor")
182
-
183
- example_images = app.get_example_images()
184
-
185
- if example_images:
186
- examples = gr.Examples(
187
- examples=example_images,
188
- inputs=image_input,
189
- label="Example Plant Disease Images"
190
- )
191
- else:
192
- gr.Markdown(
193
- """
194
- **No example images found.**
195
-
196
- To add example images:
197
- 1. Create a folder: `ui/examples/`
198
- 2. Add plant leaf images (.jpg, .png) to this folder
199
- 3. Restart the app
200
- """
201
- )
202
 
203
  with gr.Tab("Batch Processing"):
204
  gr.Markdown("### Upload multiple images for batch processing")
@@ -214,7 +233,7 @@ def create_interface():
214
  batch_output = gr.Markdown(label="Batch Results")
215
 
216
  batch_predict_btn.click(
217
- fn=app.predict_batch,
218
  inputs=[batch_input, model_selector, confidence_slider],
219
  outputs=batch_output
220
  )
 
14
  sys.path.append(str(Path(__file__).parent.parent))
15
 
16
  from model_loader import ModelLoader
17
+ import utils
18
+ from utils import *
19
+ import config
20
+ from config import *
21
 
22
 
23
  class PlantDiseaseApp:
 
26
  self.current_modelName = "CNN from Scratch"
27
  self.model = self.model_loader.loadModel(self.current_modelName)
28
  self.flagged_predictions = []
29
+ self.class_names = utils.get_class_names()
30
 
31
  def predict(self, image, modelName, confidence_threshold):
32
+ """
33
+ Predict plant disease from a single image.
34
+
35
+ Args:
36
+ image: PIL Image or numpy array from Gradio upload
37
+ modelName: Name of the model to use
38
+ confidence_threshold: float (0-100), only show predictions above this confidence
39
+
40
+ Returns:
41
+ display_predictions: dict, class_name -> probability
42
+ result_text: str, formatted top prediction info
43
+ raw_predictions: str, JSON-formatted top predictions
44
+ """
45
  if image is None:
46
  return None, "Please upload an image", ""
47
 
48
  try:
49
+ # Load model if needed
50
  if modelName != self.current_modelName:
51
+ self.model, self.class_names = self.model_loader.loadModel(modelName)
52
  self.current_modelName = modelName
53
 
54
  # Preprocess image
55
+ tensor = preprocess_image(image).to(self.model_loader.device)
 
56
 
57
+ # Model inference
58
  with torch.no_grad():
59
  logits = self.model(tensor)
60
 
61
+ # Convert logits to probabilities
62
+ probs = torch.nn.functional.softmax(logits, dim=1).cpu().numpy()[0]
63
+
64
+ # Map to class names
65
+ predictions = {name: float(prob) for name, prob in zip(self.class_names, probs)}
66
 
67
  # Filter by confidence threshold
68
+ filtered_predictions = {k: v for k, v in predictions.items() if v >= confidence_threshold / 100.0}
 
 
69
 
70
+ # Top prediction info
71
  if filtered_predictions:
72
  top_class = max(filtered_predictions.items(), key=lambda x: x[1])[0]
73
  top_prob = filtered_predictions[top_class]
74
  disease_info = get_disease_info(top_class)
75
 
76
  result_text = f"""
77
+ **Top Prediction:** {disease_info['formatted_name']}
78
+ **Confidence:** {top_prob*100:.2f}%
79
+ **Plant:** {disease_info['plant']}
80
+ **Status:** {'Healthy' if disease_info['is_healthy'] else 'Disease Detected'}
81
+ """
82
  else:
83
  result_text = "No predictions above confidence threshold"
84
 
85
  # Format for Gradio Label component
86
+ display_predictions = {format_class_name(k): v for k, v in filtered_predictions.items()}
 
 
87
 
88
+ # Raw JSON output
89
+ import json
90
+ raw_predictions = json.dumps(filtered_predictions, indent=2)
91
+
92
+ return display_predictions, result_text, raw_predictions
93
 
94
  except Exception as e:
95
  return None, f"Error during prediction: {str(e)}", ""
96
 
97
 
98
+ def flag_prediction(self, image, result_info, feedback_text):
99
+ if image is None:
100
+ return "No image uploaded."
101
+
102
+ if not feedback_text.strip():
103
+ return "Please enter feedback before submitting."
104
+
105
+ try:
106
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
107
+
108
+ entry = {
109
+ "timestamp": timestamp,
110
+ "feedback": feedback_text,
111
+ "model": self.current_modelName,
112
+ "result_info": result_info
113
+ }
114
+
115
+ self.flagged_predictions.append(entry)
116
+
117
+ return "Thanks! Your feedback has been recorded."
118
+
119
+ except Exception as e:
120
+ return f"Error saving feedback: {str(e)}"
121
 
122
  def create_interface():
123
  app = PlantDiseaseApp()
 
218
  outputs=flag_output
219
  )
220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
  with gr.Tab("Batch Processing"):
223
  gr.Markdown("### Upload multiple images for batch processing")
 
233
  batch_output = gr.Markdown(label="Batch Results")
234
 
235
  batch_predict_btn.click(
236
+ # fn=app.predict_batch,
237
  inputs=[batch_input, model_selector, confidence_slider],
238
  outputs=batch_output
239
  )
ui/classNames.txt ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apple___Apple_scab
2
+ Apple___Black_rot
3
+ Apple___Cedar_apple_rust
4
+ Apple___healthy
5
+ Background_without_leaves
6
+ Blueberry___healthy
7
+ Cherry_(including_sour)_Powdery_mildew
8
+ Cherry_(including_sour)_healthy
9
+ Corn___Cercospora_leaf_spot Gray_leaf_spot
10
+ Corn___Common_rust
11
+ Corn___Northern_Leaf_Blight
12
+ Corn___healthy
13
+ Grape___Black_rot
14
+ Grape__Esca(Black_Measles)
15
+ Grape__Leaf_blight(Isariopsis_Leaf_Spot)
16
+ Grape___healthy
17
+ Orange__Haunglongbing(Citrus_greening)
18
+ Peach___Bacterial_spot
19
+ Peach___healthy
20
+ Pepper,bell__Bacterial_spot
21
+ Pepper,bell__healthy
22
+ Potato___Early_blight
23
+ Potato___Late_blight
24
+ Potato___healthy
25
+ Raspberry___healthy
26
+ Soybean___healthy
27
+ Squash___Powdery_mildew
28
+ Strawberry___Leaf_scorch
29
+ Strawberry___healthy
30
+ Tomato___Bacterial_spot
31
+ Tomato___Early_blight
32
+ Tomato___Late_blight
33
+ Tomato___Leaf_Mold
34
+ Tomato___Septoria_leaf_spot
35
+ Tomato__Spider_mites(Two-spotted_spider_mite)
36
+ Tomato___Target_Spot
37
+ Tomato___Tomato_Yellow_Leaf_Curl_Virus
38
+ Tomato___Tomato_mosaic_virus
39
+ Tomato___healthy
ui/config.py CHANGED
@@ -5,11 +5,7 @@ MODEL_CONFIGS = {
5
  "CNN from Scratch": {
6
  "description": "Custom CNN model trained from scratch",
7
  "model_type": "cnn",
8
- "clearml_task_id": "fe14662da63d45bf9208fdf9856d2fcc"
9
- },
10
- "Transfer Learning (ResNet18)": {
11
- "description": "Fine-tuned ResNet18 model",
12
- "model_type": "resnet18",
13
- "clearml_task_id": "SET_ME_TO_YOUR_RESNET_TASK_ID"
14
  }
15
  }
 
5
  "CNN from Scratch": {
6
  "description": "Custom CNN model trained from scratch",
7
  "model_type": "cnn",
8
+ "clearml_task_id": "01345cf81fba4a2cac1176887bca9407"
9
+
 
 
 
 
10
  }
11
  }
ui/model_loader.py CHANGED
@@ -2,9 +2,13 @@ import torch
2
  import sys
3
  from pathlib import Path
4
  import config
 
 
 
5
 
6
  sys.path.append(str(Path(__file__).parent.parent))
7
 
 
8
 
9
  class ModelLoader:
10
  def __init__(self):
@@ -16,25 +20,48 @@ class ModelLoader:
16
 
17
  if not modelConfig:
18
  raise ValueError(f"ClearML configuration not found for model: {modelName}")
19
-
20
  taskID = modelConfig['clearml_task_id']
21
- modelType = modelConfig['model_type']
22
 
23
  try:
24
- print(f"attemtping to fetch '{modelName}' from clearML task: {taskID}")
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- modelObject = Model(taskID=taskID)
27
- modelPath = modelObject.get_local_copy()
 
 
28
 
29
- model = self.loadRealModel(modelName, modelPath, modelType)
 
 
 
 
 
 
 
 
30
 
31
  return model
32
-
33
  except Exception as e:
34
  print(f"Error loading from ClearML for {modelName}: {e}")
35
  raise RuntimeError(f"Failed to load model from ClearML: {e}")
 
36
 
37
- def loadModel(self, modelName) :
38
  if modelName in self.modelCache:
39
  return self.modelCache[modelName]
40
 
 
2
  import sys
3
  from pathlib import Path
4
  import config
5
+ import utils
6
+ from clearml import Task
7
+ from models.modelOne import modelOne
8
 
9
  sys.path.append(str(Path(__file__).parent.parent))
10
 
11
+ MODEL_ARTIFACT_NAME = 'best_model'
12
 
13
  class ModelLoader:
14
  def __init__(self):
 
20
 
21
  if not modelConfig:
22
  raise ValueError(f"ClearML configuration not found for model: {modelName}")
23
+
24
  taskID = modelConfig['clearml_task_id']
 
25
 
26
  try:
27
+ print(f"Attempting to fetch '{modelName}' from ClearML task: {taskID}")
28
+
29
+ task = Task.get_task(task_id=taskID)
30
+ print("Available artifacts:", task.artifacts.keys())
31
+
32
+ # Fetch the artifact 'model_one.pt'
33
+ artifact = task.artifacts.get(MODEL_ARTIFACT_NAME)
34
+
35
+ if artifact is None:
36
+ raise RuntimeError(
37
+ f"Artifact '{MODEL_ARTIFACT_NAME}' not found in ClearML task {taskID}"
38
+ )
39
+
40
+ modelPath = artifact.get_local_copy()
41
 
42
+ if modelPath is None:
43
+ raise RuntimeError(
44
+ f"Artifact '{MODEL_ARTIFACT_NAME}' could not be downloaded (returned None)"
45
+ )
46
 
47
+ print(f"Weights downloaded to: {modelPath}")
48
+
49
+ # Load PyTorch model
50
+ model = modelOne(noOfClasses=39)
51
+ stateDict = torch.load(modelPath, map_location=self.device)
52
+ model.load_state_dict(stateDict)
53
+
54
+ model.to(self.device)
55
+ model.eval()
56
 
57
  return model
58
+
59
  except Exception as e:
60
  print(f"Error loading from ClearML for {modelName}: {e}")
61
  raise RuntimeError(f"Failed to load model from ClearML: {e}")
62
+
63
 
64
+ def loadModel(self, modelName):
65
  if modelName in self.modelCache:
66
  return self.modelCache[modelName]
67
 
ui/utils.py CHANGED
@@ -6,98 +6,72 @@ import torch
6
  import numpy as np
7
  from PIL import Image
8
  import torchvision.transforms as transforms
9
- import config
10
 
 
 
 
 
 
 
 
11
 
12
- def preprocess_image(image, image_size=config.IMAGE_SIZE):
13
- """
14
- Preprocess image for model input
15
 
16
- Args:
17
- image: PIL Image or numpy array
18
- image_size: Target size (height, width)
19
 
20
- Returns:
21
- Preprocessed tensor ready for model
 
 
 
 
 
 
 
22
  """
23
- # Convert to PIL Image if numpy array
24
  if isinstance(image, np.ndarray):
25
  image = Image.fromarray(image.astype('uint8'))
26
 
27
- # Convert RGBA to RGB if necessary
28
  if image.mode == 'RGBA':
29
  image = image.convert('RGB')
30
 
31
- # Define preprocessing transforms
32
  transform = transforms.Compose([
33
- transforms.Resize(image_size),
34
  transforms.ToTensor(),
35
- transforms.Normalize(mean=config.NORMALIZE_MEAN, std=config.NORMALIZE_STD)
36
  ])
37
 
38
- # Apply transforms
39
  tensor = transform(image)
 
40
 
41
- # Add batch dimension
42
- tensor = tensor.unsqueeze(0)
43
 
44
- return tensor
45
-
46
-
47
- def postprocess_predictions(logits, class_names=config.CLASS_NAMES, top_k=config.TOP_K_PREDICTIONS):
48
  """
49
- Convert model logits to human-readable predictions
50
-
51
- Args:
52
- logits: Raw model output
53
- class_names: List of class names
54
- top_k: Number of top predictions to return
55
-
56
- Returns:
57
- Dictionary of predictions with confidences
58
  """
59
- # Convert logits to probabilities using softmax
60
- probs = torch.nn.functional.softmax(logits, dim=1)
61
 
62
- # Convert to numpy
63
  probs = probs.cpu().detach().numpy()[0]
64
 
65
- # Create predictions dictionary
66
  predictions = {name: float(prob) for name, prob in zip(class_names, probs)}
67
-
68
- # Get top-k predictions
69
  top_predictions = sorted(predictions.items(), key=lambda x: x[1], reverse=True)[:top_k]
70
 
71
  return dict(top_predictions), predictions
72
 
73
 
74
- def format_prediction_for_display(predictions):
75
  """
76
- Format predictions for Gradio display
77
-
78
- Args:
79
- predictions: Dictionary of class names and probabilities
80
-
81
- Returns:
82
- Dictionary formatted for Gradio Label component
83
  """
84
- # Filter out very low confidence predictions
85
- filtered = {k: v for k, v in predictions.items() if v >= config.CONFIDENCE_THRESHOLD}
86
-
87
- return filtered
88
 
89
 
90
  def format_class_name(class_name):
91
  """
92
- Format class name for better readability
93
-
94
- Args:
95
- class_name: Original class name (e.g., "Tomato___Late_blight")
96
-
97
- Returns:
98
- Formatted class name (e.g., "Tomato - Late blight")
99
  """
100
- # Replace underscores with spaces and split on ___
101
  parts = class_name.split("___")
102
 
103
  if len(parts) == 2:
@@ -105,74 +79,52 @@ def format_class_name(class_name):
105
  plant = plant.replace("_", " ")
106
  disease = disease.replace("_", " ")
107
  return f"{plant} - {disease}"
108
- else:
109
- return class_name.replace("_", " ")
110
 
111
 
112
  def get_disease_info(class_name):
113
  """
114
- Get information about a disease (for future enhancement)
115
-
116
- Args:
117
- class_name: Disease class name
118
-
119
- Returns:
120
- Dictionary with disease information
121
  """
122
- # This is a placeholder - you could expand this with actual disease information
123
  parts = class_name.split("___")
124
 
125
- info = {
126
  "plant": parts[0].replace("_", " ") if len(parts) > 0 else "Unknown",
127
  "disease": parts[1].replace("_", " ") if len(parts) > 1 else "Unknown",
128
  "is_healthy": "healthy" in class_name.lower(),
129
  "formatted_name": format_class_name(class_name)
130
  }
131
 
132
- return info
133
-
134
 
135
  def batch_preprocess_images(images):
136
  """
137
- Preprocess multiple images for batch prediction
138
-
139
- Args:
140
- images: List of PIL Images or numpy arrays
141
-
142
- Returns:
143
- Batched tensor ready for model
144
  """
145
  tensors = [preprocess_image(img) for img in images]
146
- batch = torch.cat(tensors, dim=0)
147
- return batch
148
 
149
 
150
  def create_confidence_label(predictions, top_k=5):
151
  """
152
- Create a formatted string showing top predictions
153
-
154
- Args:
155
- predictions: Dictionary of predictions
156
- top_k: Number of top predictions to show
157
-
158
- Returns:
159
- Formatted string
160
  """
161
  top_preds = sorted(predictions.items(), key=lambda x: x[1], reverse=True)[:top_k]
162
 
163
- lines = []
164
- for i, (class_name, prob) in enumerate(top_preds, 1):
165
- formatted_name = format_class_name(class_name)
166
- lines.append(f"{i}. {formatted_name}: {prob*100:.2f}%")
167
-
168
  return "\n".join(lines)
169
 
170
 
 
 
 
 
171
  if __name__ == "__main__":
172
- # Test utilities
173
  print("Testing utility functions...")
174
 
175
- # Test class name formatting
176
  test_names = [
177
  "Tomato___Late_blight",
178
  "Apple___healthy",
@@ -183,7 +135,6 @@ if __name__ == "__main__":
183
  for name in test_names:
184
  print(f" {name} -> {format_class_name(name)}")
185
 
186
- # Test disease info
187
  print("\nDisease info:")
188
  for name in test_names:
189
  info = get_disease_info(name)
@@ -192,19 +143,8 @@ if __name__ == "__main__":
192
  print(f" Disease: {info['disease']}")
193
  print(f" Healthy: {info['is_healthy']}")
194
 
195
- # Test image preprocessing
196
  print("\nImage preprocessing:")
197
  dummy_image = Image.new('RGB', (512, 512), color='red')
198
  tensor = preprocess_image(dummy_image)
199
  print(f" Input size: {dummy_image.size}")
200
  print(f" Output tensor shape: {tensor.shape}")
201
-
202
- # Test mock predictions
203
- print("\nMock predictions:")
204
- from models.mock_model import create_mock_predictions
205
- preds = create_mock_predictions(config.CLASS_NAMES)
206
- top_preds, all_preds = postprocess_predictions(
207
- torch.tensor([list(preds.values())]),
208
- config.CLASS_NAMES
209
- )
210
- print(create_confidence_label(top_preds))
 
6
  import numpy as np
7
  from PIL import Image
8
  import torchvision.transforms as transforms
9
+ import os
10
 
11
+ IMAGE_SIZE = (256, 256)
12
+
13
+ NORMALIZE_MEAN = [0.485, 0.456, 0.406]
14
+ NORMALIZE_STD = [0.229, 0.224, 0.225]
15
+
16
+ TOP_K_PREDICTIONS = 5
17
+ CONFIDENCE_THRESHOLD = 0.01
18
 
 
 
 
19
 
20
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
 
 
21
 
22
+ # Path to classNames.txt relative to this file
23
+ CLASS_NAMES_FILE = os.path.join(BASE_DIR, "classNames.txt")
24
+
25
+ with open(CLASS_NAMES_FILE, "r") as f:
26
+ CLASS_NAMES = [line.strip() for line in f.readlines() if line.strip()]
27
+
28
+ def preprocess_image(image):
29
+ """
30
+ Preprocess image for model input
31
  """
 
32
  if isinstance(image, np.ndarray):
33
  image = Image.fromarray(image.astype('uint8'))
34
 
 
35
  if image.mode == 'RGBA':
36
  image = image.convert('RGB')
37
 
 
38
  transform = transforms.Compose([
39
+ transforms.Resize(IMAGE_SIZE),
40
  transforms.ToTensor(),
41
+ transforms.Normalize(NORMALIZE_MEAN, NORMALIZE_STD)
42
  ])
43
 
 
44
  tensor = transform(image)
45
+ return tensor.unsqueeze(0)
46
 
 
 
47
 
48
+ def postprocess_predictions(logits, class_names=None, top_k=TOP_K_PREDICTIONS):
 
 
 
49
  """
50
+ Convert logits to formatted predictions
 
 
 
 
 
 
 
 
51
  """
52
+ if class_names is None:
53
+ class_names = CLASS_NAMES
54
 
55
+ probs = torch.nn.functional.softmax(logits, dim=1)
56
  probs = probs.cpu().detach().numpy()[0]
57
 
 
58
  predictions = {name: float(prob) for name, prob in zip(class_names, probs)}
 
 
59
  top_predictions = sorted(predictions.items(), key=lambda x: x[1], reverse=True)[:top_k]
60
 
61
  return dict(top_predictions), predictions
62
 
63
 
64
+ def format_prediction_for_display(predictions, confidence_threshold=CONFIDENCE_THRESHOLD):
65
  """
66
+ Filter predictions for Gradio display
 
 
 
 
 
 
67
  """
68
+ return {k: v for k, v in predictions.items() if v >= confidence_threshold}
 
 
 
69
 
70
 
71
  def format_class_name(class_name):
72
  """
73
+ Format class name into readable form
 
 
 
 
 
 
74
  """
 
75
  parts = class_name.split("___")
76
 
77
  if len(parts) == 2:
 
79
  plant = plant.replace("_", " ")
80
  disease = disease.replace("_", " ")
81
  return f"{plant} - {disease}"
82
+
83
+ return class_name.replace("_", " ")
84
 
85
 
86
  def get_disease_info(class_name):
87
  """
88
+ Extract structured disease info from class name
 
 
 
 
 
 
89
  """
 
90
  parts = class_name.split("___")
91
 
92
+ return {
93
  "plant": parts[0].replace("_", " ") if len(parts) > 0 else "Unknown",
94
  "disease": parts[1].replace("_", " ") if len(parts) > 1 else "Unknown",
95
  "is_healthy": "healthy" in class_name.lower(),
96
  "formatted_name": format_class_name(class_name)
97
  }
98
 
 
 
99
 
100
  def batch_preprocess_images(images):
101
  """
102
+ Preprocess a list of images into a batch tensor
 
 
 
 
 
 
103
  """
104
  tensors = [preprocess_image(img) for img in images]
105
+ return torch.cat(tensors, dim=0)
 
106
 
107
 
108
  def create_confidence_label(predictions, top_k=5):
109
  """
110
+ Render a formatted multiline prediction list
 
 
 
 
 
 
 
111
  """
112
  top_preds = sorted(predictions.items(), key=lambda x: x[1], reverse=True)[:top_k]
113
 
114
+ lines = [
115
+ f"{i}. {format_class_name(name)}: {prob*100:.2f}%"
116
+ for i, (name, prob) in enumerate(top_preds, 1)
117
+ ]
 
118
  return "\n".join(lines)
119
 
120
 
121
+ def get_class_names():
122
+ """Return the loaded class names from the txt file."""
123
+ return CLASS_NAMES
124
+
125
  if __name__ == "__main__":
 
126
  print("Testing utility functions...")
127
 
 
128
  test_names = [
129
  "Tomato___Late_blight",
130
  "Apple___healthy",
 
135
  for name in test_names:
136
  print(f" {name} -> {format_class_name(name)}")
137
 
 
138
  print("\nDisease info:")
139
  for name in test_names:
140
  info = get_disease_info(name)
 
143
  print(f" Disease: {info['disease']}")
144
  print(f" Healthy: {info['is_healthy']}")
145
 
 
146
  print("\nImage preprocessing:")
147
  dummy_image = Image.new('RGB', (512, 512), color='red')
148
  tensor = preprocess_image(dummy_image)
149
  print(f" Input size: {dummy_image.size}")
150
  print(f" Output tensor shape: {tensor.shape}")