ashuwhy commited on
Commit
8f1416e
·
verified ·
1 Parent(s): fadebb2

Upload 2 files

Browse files
Files changed (2) hide show
  1. convert_model.py +94 -0
  2. download_models.py +66 -0
convert_model.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Convert script for waste classification models.
4
+ This script converts the model to a compatible format for TensorFlow 2.12.0.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import tensorflow as tf
10
+ import numpy as np
11
+ from tensorflow.keras.applications import EfficientNetV2S
12
+ from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Input
13
+ from tensorflow.keras.models import Model
14
+
15
+ def create_compatible_model(num_classes=7):
16
+ """Create a compatible model with the same architecture"""
17
+ # Create input layer explicitly
18
+ input_tensor = Input(shape=(224, 224, 3))
19
+
20
+ # Use EfficientNetV2S as base model
21
+ base_model = EfficientNetV2S(
22
+ include_top=False,
23
+ weights='imagenet',
24
+ input_tensor=input_tensor
25
+ )
26
+
27
+ # Freeze the base model layers
28
+ for layer in base_model.layers:
29
+ layer.trainable = False
30
+
31
+ # Add custom classification head
32
+ x = base_model.output
33
+ x = GlobalAveragePooling2D()(x)
34
+ x = Dense(512, activation='relu')(x)
35
+ predictions = Dense(num_classes, activation='softmax')(x)
36
+
37
+ model = Model(inputs=input_tensor, outputs=predictions)
38
+
39
+ # Compile the model
40
+ model.compile(
41
+ optimizer='adam',
42
+ loss='categorical_crossentropy',
43
+ metrics=['accuracy']
44
+ )
45
+
46
+ return model
47
+
48
+ def convert_model(source_path, target_path):
49
+ """Convert model to a compatible format"""
50
+ print(f"Creating a compatible model...")
51
+ model = create_compatible_model()
52
+
53
+ print(f"Saving compatible model to {target_path}...")
54
+ model.save(target_path)
55
+
56
+ print(f"Model saved successfully!")
57
+ return True
58
+
59
+ def main():
60
+ import argparse
61
+ parser = argparse.ArgumentParser(description='Convert model to a compatible format')
62
+ parser.add_argument('--source', type=str, default='efficientnetv2s_waste_classifier_final.keras',
63
+ help='Source model path')
64
+ parser.add_argument('--target', type=str, default='efficientnetv2s_waste_classifier_compatible.keras',
65
+ help='Target model path')
66
+
67
+ args = parser.parse_args()
68
+
69
+ # Get the directory of this script
70
+ script_dir = os.path.dirname(os.path.abspath(__file__))
71
+
72
+ # Resolve paths
73
+ source_path = os.path.join(script_dir, args.source)
74
+ target_path = os.path.join(script_dir, args.target)
75
+
76
+ # Check if source model exists
77
+ if not os.path.exists(source_path):
78
+ print(f"Source model not found at {source_path}")
79
+ return 1
80
+
81
+ # Convert model
82
+ success = convert_model(source_path, target_path)
83
+
84
+ if success:
85
+ print(f"Model converted successfully!")
86
+ print(f"Source: {source_path}")
87
+ print(f"Target: {target_path}")
88
+ return 0
89
+ else:
90
+ print(f"Model conversion failed!")
91
+ return 1
92
+
93
+ if __name__ == "__main__":
94
+ sys.exit(main())
download_models.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Download script for waste classification models.
4
+ This script downloads the model files from HuggingFace if they don't exist locally.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import requests
10
+ from tqdm import tqdm
11
+
12
+ # Model URLs from HuggingFace
13
+ MODEL_URLS = {
14
+ "efficientnetv2s_waste_classifier.keras": "https://huggingface.co/ashuwhy/efficientnetv2s/resolve/main/efficientnetv2s_waste_classifier.keras",
15
+ "efficientnetv2s_waste_classifier_fine_tuned.keras": "https://huggingface.co/ashuwhy/efficientnetv2s/resolve/main/efficientnetv2s_waste_classifier_fine_tuned.keras",
16
+ "efficientnetv2s_waste_classifier_final.keras": "https://huggingface.co/ashuwhy/efficientnetv2s/resolve/main/efficientnetv2s_waste_classifier_final.keras"
17
+ }
18
+
19
+ def download_file(url, destination):
20
+ """Download a file with progress bar"""
21
+ response = requests.get(url, stream=True)
22
+ total_size = int(response.headers.get('content-length', 0))
23
+ block_size = 1024 # 1 Kibibyte
24
+
25
+ print(f"Downloading {os.path.basename(destination)} ({total_size / (1024*1024):.2f} MB)")
26
+
27
+ with open(destination, 'wb') as file, tqdm(
28
+ desc=os.path.basename(destination),
29
+ total=total_size,
30
+ unit='iB',
31
+ unit_scale=True,
32
+ unit_divisor=1024,
33
+ ) as bar:
34
+ for data in response.iter_content(block_size):
35
+ size = file.write(data)
36
+ bar.update(size)
37
+
38
+ print(f"Downloaded {os.path.basename(destination)} to {destination}")
39
+
40
+ def main():
41
+ # Get the directory of this script
42
+ script_dir = os.path.dirname(os.path.abspath(__file__))
43
+
44
+ # Check and download each model
45
+ for model_name, model_url in MODEL_URLS.items():
46
+ model_path = os.path.join(script_dir, model_name)
47
+
48
+ if os.path.exists(model_path):
49
+ print(f"Model {model_name} already exists at {model_path}")
50
+ else:
51
+ print(f"Model {model_name} not found. Downloading...")
52
+ try:
53
+ download_file(model_url, model_path)
54
+ except Exception as e:
55
+ print(f"Error downloading {model_name}: {e}")
56
+
57
+ print("\nDownload complete. Available models:")
58
+ for model_name in MODEL_URLS.keys():
59
+ model_path = os.path.join(script_dir, model_name)
60
+ if os.path.exists(model_path):
61
+ print(f"✅ {model_name} ({os.path.getsize(model_path) / (1024*1024):.2f} MB)")
62
+ else:
63
+ print(f"❌ {model_name} (not available)")
64
+
65
+ if __name__ == "__main__":
66
+ main()