Spaces:
				
			
			
	
			
			
		Runtime error
		
	
	
	
			
			
	
	
	
	
		
		
		Runtime error
		
	Update app.py
Browse files
    	
        app.py
    CHANGED
    
    | @@ -1,320 +1,320 @@ | |
| 1 | 
            -
            import random
         | 
| 2 | 
            -
             | 
| 3 | 
            -
            import gradio as gr
         | 
| 4 | 
            -
            import torch
         | 
| 5 | 
            -
            import torchvision
         | 
| 6 | 
            -
            import torchvision.transforms as transforms
         | 
| 7 | 
            -
            from PIL import Image
         | 
| 8 | 
            -
            from torch import nn
         | 
| 9 | 
            -
            from torchvision.models import mobilenet_v2, resnet18
         | 
| 10 | 
            -
            from torchvision.transforms.functional import InterpolationMode
         | 
| 11 | 
            -
             | 
| 12 | 
            -
            datasets_n_classes = {
         | 
| 13 | 
            -
                "Imagenette": 10,
         | 
| 14 | 
            -
                "Imagewoof": 10,
         | 
| 15 | 
            -
                "Stanford_dogs": 120,
         | 
| 16 | 
            -
            }
         | 
| 17 | 
            -
             | 
| 18 | 
            -
            datasets_model_types = {
         | 
| 19 | 
            -
                "Imagenette": [
         | 
| 20 | 
            -
                    "base_200",
         | 
| 21 | 
            -
                    "base_200+100",
         | 
| 22 | 
            -
                    "synthetic_200",
         | 
| 23 | 
            -
                    "augment_noisy_200",
         | 
| 24 | 
            -
                    "augment_noisy_200+100",
         | 
| 25 | 
            -
                    "augment_clean_200",
         | 
| 26 | 
            -
                ],
         | 
| 27 | 
            -
                "Imagewoof": [
         | 
| 28 | 
            -
                    "base_200",
         | 
| 29 | 
            -
                    "base_200+100",
         | 
| 30 | 
            -
                    "synthetic_200",
         | 
| 31 | 
            -
                    "augment_noisy_200",
         | 
| 32 | 
            -
                    "augment_noisy_200+100",
         | 
| 33 | 
            -
                    "augment_clean_200",
         | 
| 34 | 
            -
                ],
         | 
| 35 | 
            -
                "Stanford_dogs": [
         | 
| 36 | 
            -
                    "base_200",
         | 
| 37 | 
            -
                    "base_200+100",
         | 
| 38 | 
            -
                    "synthetic_200",
         | 
| 39 | 
            -
                    "augment_noisy_200",
         | 
| 40 | 
            -
                    "augment_noisy_200+100",
         | 
| 41 | 
            -
                ],
         | 
| 42 | 
            -
            }
         | 
| 43 | 
            -
             | 
| 44 | 
            -
            model_arch = ["resnet18", "mobilenet_v2"]
         | 
| 45 | 
            -
             | 
| 46 | 
            -
            list_200 = [
         | 
| 47 | 
            -
                "Original",
         | 
| 48 | 
            -
                "Synthetic",
         | 
| 49 | 
            -
                "Original + Synthetic (Noisy)",
         | 
| 50 | 
            -
                "Original + Synthetic (Clean)",
         | 
| 51 | 
            -
            ]
         | 
| 52 | 
            -
             | 
| 53 | 
            -
            list_200_100 = ["Base+100", "AugmentNoisy+100"]
         | 
| 54 | 
            -
             | 
| 55 | 
            -
            methods_map = {
         | 
| 56 | 
            -
                "200 Epochs": list_200,
         | 
| 57 | 
            -
                "200 Epochs on Original + 100": list_200_100,
         | 
| 58 | 
            -
            }
         | 
| 59 | 
            -
             | 
| 60 | 
            -
            label_map = dict()
         | 
| 61 | 
            -
            label_map["Imagenette (10 classes)"] = "Imagenette"
         | 
| 62 | 
            -
            label_map["Imagewoof (10 classes)"] = "Imagewoof"
         | 
| 63 | 
            -
            label_map["Stanford Dogs (120 classes)"] = "Stanford_dogs"
         | 
| 64 | 
            -
            label_map["ResNet-18"] = "resnet18"
         | 
| 65 | 
            -
            label_map["MobileNetV2"] = "mobilenet_v2"
         | 
| 66 | 
            -
            label_map["200 Epochs"] = "200"
         | 
| 67 | 
            -
            label_map["200 Epochs on Original + 100"] = "200+100"
         | 
| 68 | 
            -
            label_map["Original"] = "base"
         | 
| 69 | 
            -
            label_map["Synthetic"] = "synthetic"
         | 
| 70 | 
            -
            label_map["Original + Synthetic (Noisy)"] = "augment_noisy"
         | 
| 71 | 
            -
            label_map["Original + Synthetic (Clean)"] = "augment_clean"
         | 
| 72 | 
            -
            label_map["Base+100"] = "base"
         | 
| 73 | 
            -
            label_map["AugmentNoisy+100"] = "augment_noisy"
         | 
| 74 | 
            -
             | 
| 75 | 
            -
            dataset_models = dict()
         | 
| 76 | 
            -
            for dataset, n_classes in datasets_n_classes.items():
         | 
| 77 | 
            -
                models = dict()
         | 
| 78 | 
            -
                for model_type in datasets_model_types[dataset]:
         | 
| 79 | 
            -
                    for arch in model_arch:
         | 
| 80 | 
            -
                        if arch == "resnet18":
         | 
| 81 | 
            -
                            model = resnet18(weights=None, num_classes=n_classes)
         | 
| 82 | 
            -
                            models[f"{arch}_{model_type}"] = (
         | 
| 83 | 
            -
                                model,
         | 
| 84 | 
            -
                                f"./models/{arch}/{dataset}/{dataset}_{model_type}.pth",
         | 
| 85 | 
            -
                            )
         | 
| 86 | 
            -
                        elif arch == "mobilenet_v2":
         | 
| 87 | 
            -
                            model = mobilenet_v2(weights=None, num_classes=n_classes)
         | 
| 88 | 
            -
                            models[f"{arch}_{model_type}"] = (
         | 
| 89 | 
            -
                                model,
         | 
| 90 | 
            -
                                f"./models/{arch}/{dataset}/{dataset}_{model_type}.pth",
         | 
| 91 | 
            -
                            )
         | 
| 92 | 
            -
                        else:
         | 
| 93 | 
            -
                            raise ValueError(f"Model architecture unavailable: {arch}")
         | 
| 94 | 
            -
                dataset_models[dataset] = models
         | 
| 95 | 
            -
             | 
| 96 | 
            -
             | 
| 97 | 
            -
            def get_random_image(dataset, label_map=label_map) -> Image:
         | 
| 98 | 
            -
                dataset_root = f"./data/{label_map[dataset]}/val"
         | 
| 99 | 
            -
                dataset_img = torchvision.datasets.ImageFolder(
         | 
| 100 | 
            -
                    dataset_root,
         | 
| 101 | 
            -
                    transforms.Compose([transforms.PILToTensor()]),
         | 
| 102 | 
            -
                )
         | 
| 103 | 
            -
                random_idx = random.randint(0, len(dataset_img) - 1)
         | 
| 104 | 
            -
                image, _ = dataset_img[random_idx]
         | 
| 105 | 
            -
                image = transforms.ToPILImage()(image)
         | 
| 106 | 
            -
                image = image.resize(
         | 
| 107 | 
            -
                    (256, 256),
         | 
| 108 | 
            -
                )
         | 
| 109 | 
            -
                return image
         | 
| 110 | 
            -
             | 
| 111 | 
            -
             | 
| 112 | 
            -
            def load_model(model_dict, model_name: str) -> nn.Module:
         | 
| 113 | 
            -
                model_name_lower = model_name.lower()
         | 
| 114 | 
            -
                if model_name_lower in model_dict:
         | 
| 115 | 
            -
                    model = model_dict[model_name_lower][0]
         | 
| 116 | 
            -
                    model_path = model_dict[model_name_lower][1]
         | 
| 117 | 
            -
                    if torch.cuda.is_available():
         | 
| 118 | 
            -
                        checkpoint = torch.load(model_path)
         | 
| 119 | 
            -
                    else:
         | 
| 120 | 
            -
                        checkpoint = torch.load(model_path, map_location="cpu")
         | 
| 121 | 
            -
                    if "setup" in checkpoint:
         | 
| 122 | 
            -
                        if checkpoint["setup"]["distributed"]:
         | 
| 123 | 
            -
                            torch.nn.modules.utils.consume_prefix_in_state_dict_if_present(
         | 
| 124 | 
            -
                                checkpoint["model"], "module."
         | 
| 125 | 
            -
                            )
         | 
| 126 | 
            -
                        model.load_state_dict(checkpoint["model"])
         | 
| 127 | 
            -
                    else:
         | 
| 128 | 
            -
                        model.load_state_dict(checkpoint)
         | 
| 129 | 
            -
                    return model
         | 
| 130 | 
            -
                else:
         | 
| 131 | 
            -
                    raise ValueError(
         | 
| 132 | 
            -
                        f"Model {model_name} is not available for image prediction. Please choose from {[name.capitalize() for name in model_dict.keys()]}."
         | 
| 133 | 
            -
                    )
         | 
| 134 | 
            -
             | 
| 135 | 
            -
             | 
| 136 | 
            -
            def postprocess_default(labels, output) -> dict:
         | 
| 137 | 
            -
                probabilities = nn.functional.softmax(output[0], dim=0)
         | 
| 138 | 
            -
                top_prob, top_catid = torch.topk(probabilities, 5)
         | 
| 139 | 
            -
                confidences = {
         | 
| 140 | 
            -
                    labels[top_catid.tolist()[i]]: top_prob.tolist()[i]
         | 
| 141 | 
            -
                    for i in range(top_prob.shape[0])
         | 
| 142 | 
            -
                }
         | 
| 143 | 
            -
                return confidences
         | 
| 144 | 
            -
             | 
| 145 | 
            -
             | 
| 146 | 
            -
            def classify(
         | 
| 147 | 
            -
                input_image: Image,
         | 
| 148 | 
            -
                dataset_type: str,
         | 
| 149 | 
            -
                arch_type: str,
         | 
| 150 | 
            -
                methods: str,
         | 
| 151 | 
            -
                training_ds: str,
         | 
| 152 | 
            -
                dataset_models=dataset_models,
         | 
| 153 | 
            -
                label_map=label_map,
         | 
| 154 | 
            -
            ) -> dict:
         | 
| 155 | 
            -
                for i in [dataset_type, arch_type, methods, training_ds]:
         | 
| 156 | 
            -
                    if i is None:
         | 
| 157 | 
            -
                        raise ValueError("Please select all options.")
         | 
| 158 | 
            -
                dataset_type = label_map[dataset_type]
         | 
| 159 | 
            -
                arch_type = label_map[arch_type]
         | 
| 160 | 
            -
                methods = label_map[methods]
         | 
| 161 | 
            -
                training_ds = label_map[training_ds]
         | 
| 162 | 
            -
                preprocess_input = transforms.Compose(
         | 
| 163 | 
            -
                    [
         | 
| 164 | 
            -
                        transforms.Resize(
         | 
| 165 | 
            -
                            256,
         | 
| 166 | 
            -
                            interpolation=InterpolationMode.BILINEAR,
         | 
| 167 | 
            -
                            antialias=True,
         | 
| 168 | 
            -
                        ),
         | 
| 169 | 
            -
                        transforms.CenterCrop(224),
         | 
| 170 | 
            -
                        transforms.ToTensor(),
         | 
| 171 | 
            -
                        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
         | 
| 172 | 
            -
                    ]
         | 
| 173 | 
            -
                )
         | 
| 174 | 
            -
                if input_image is None:
         | 
| 175 | 
            -
                    raise ValueError("No image was provided.")
         | 
| 176 | 
            -
                input_tensor: torch.Tensor = preprocess_input(input_image)
         | 
| 177 | 
            -
                input_batch = input_tensor.unsqueeze(0)
         | 
| 178 | 
            -
                model = load_model(
         | 
| 179 | 
            -
                    dataset_models[dataset_type], f"{arch_type}_{training_ds}_{methods}"
         | 
| 180 | 
            -
                )
         | 
| 181 | 
            -
             | 
| 182 | 
            -
                if torch.cuda.is_available():
         | 
| 183 | 
            -
                    input_batch = input_batch.to("cuda")
         | 
| 184 | 
            -
                    model.to("cuda")
         | 
| 185 | 
            -
             | 
| 186 | 
            -
                model.eval()
         | 
| 187 | 
            -
                with torch.inference_mode():
         | 
| 188 | 
            -
                    output: torch.Tensor = model(input_batch)
         | 
| 189 | 
            -
                with open(f"./data/{dataset_type}.txt", "r") as f:
         | 
| 190 | 
            -
                    labels = {i: line.strip() for i, line in enumerate(f.readlines())}
         | 
| 191 | 
            -
                return postprocess_default(labels, output)
         | 
| 192 | 
            -
             | 
| 193 | 
            -
             | 
| 194 | 
            -
            def update_methods(method, ds_type):
         | 
| 195 | 
            -
                if ds_type == "Stanford Dogs (120 classes)" and method == "200 Epochs":
         | 
| 196 | 
            -
                    methods = list_200[:-1]
         | 
| 197 | 
            -
                else:
         | 
| 198 | 
            -
                    methods = methods_map[method]
         | 
| 199 | 
            -
                return gr.update(choices=methods, value=None)
         | 
| 200 | 
            -
             | 
| 201 | 
            -
             | 
| 202 | 
            -
            def downloadModel(
         | 
| 203 | 
            -
                dataset_type, arch_type, methods, training_ds, dataset_models=dataset_models
         | 
| 204 | 
            -
            ):
         | 
| 205 | 
            -
                for i in [dataset_type, arch_type, methods, training_ds]:
         | 
| 206 | 
            -
                    if i is None:
         | 
| 207 | 
            -
                        return gr.update(label="Select Model", value=None)
         | 
| 208 | 
            -
                dataset_type = label_map[dataset_type]
         | 
| 209 | 
            -
                arch_type = label_map[arch_type]
         | 
| 210 | 
            -
                methods = label_map[methods]
         | 
| 211 | 
            -
                training_ds = label_map[training_ds]
         | 
| 212 | 
            -
                if f"{arch_type}_{training_ds}_{methods}" not in dataset_models[dataset_type]:
         | 
| 213 | 
            -
                    return gr.update(label="Select Model", value=None)
         | 
| 214 | 
            -
                model_path = dataset_models[dataset_type][f"{arch_type}_{training_ds}_{methods}"][1]
         | 
| 215 | 
            -
                return gr.update(
         | 
| 216 | 
            -
                    label=f"Download Model: '{dataset_type}_{arch_type}_{training_ds}_{methods}'",
         | 
| 217 | 
            -
                    value=model_path,
         | 
| 218 | 
            -
                )
         | 
| 219 | 
            -
             | 
| 220 | 
            -
             | 
| 221 | 
            -
            if __name__ == "__main__":
         | 
| 222 | 
            -
                with gr.Blocks(title="Generative Augmented Image Classifiers") as demo:
         | 
| 223 | 
            -
                    gr.Markdown(
         | 
| 224 | 
            -
                        """
         | 
| 225 | 
            -
            # Generative Augmented Image Classifiers
         | 
| 226 | 
            -
            Main GitHub Repo: [Generative Data Augmentation](https://github.com/zhulinchng/generative-data-augmentation) | Generative Data Augmentation Demo: [Generative Data Augmented](https://huggingface.co/spaces/czl/generative-data-augmentation-demo).
         | 
| 227 | 
            -
            """
         | 
| 228 | 
            -
                    )
         | 
| 229 | 
            -
                    with gr.Row():
         | 
| 230 | 
            -
                        with gr.Column():
         | 
| 231 | 
            -
                            dataset_type = gr.Radio(
         | 
| 232 | 
            -
                                choices=[
         | 
| 233 | 
            -
                                    "Imagenette (10 classes)",
         | 
| 234 | 
            -
                                    "Imagewoof (10 classes)",
         | 
| 235 | 
            -
                                    "Stanford Dogs (120 classes)",
         | 
| 236 | 
            -
                                ],
         | 
| 237 | 
            -
                                label="Dataset",
         | 
| 238 | 
            -
                                value="Imagenette (10 classes)",
         | 
| 239 | 
            -
                            )
         | 
| 240 | 
            -
                            arch_type = gr.Radio(
         | 
| 241 | 
            -
                                choices=["ResNet-18", "MobileNetV2"],
         | 
| 242 | 
            -
                                label="Model Architecture",
         | 
| 243 | 
            -
                                value="ResNet-18",
         | 
| 244 | 
            -
                                interactive=True,
         | 
| 245 | 
            -
                            )
         | 
| 246 | 
            -
                            methods = gr.Radio(
         | 
| 247 | 
            -
                                label="Methods",
         | 
| 248 | 
            -
                                choices=["200 Epochs", "200 Epochs on Original + 100"],
         | 
| 249 | 
            -
                                interactive=True,
         | 
| 250 | 
            -
                                value="200 Epochs",
         | 
| 251 | 
            -
                            )
         | 
| 252 | 
            -
                            training_ds = gr.Radio(
         | 
| 253 | 
            -
                                label="Training Dataset",
         | 
| 254 | 
            -
                                choices=methods_map["200 Epochs"],
         | 
| 255 | 
            -
                                interactive=True,
         | 
| 256 | 
            -
                                value="Original",
         | 
| 257 | 
            -
                            )
         | 
| 258 | 
            -
                            dataset_type.change(
         | 
| 259 | 
            -
                                fn=update_methods,
         | 
| 260 | 
            -
                                inputs=[methods, dataset_type],
         | 
| 261 | 
            -
                                outputs=[training_ds],
         | 
| 262 | 
            -
                            )
         | 
| 263 | 
            -
                            methods.change(
         | 
| 264 | 
            -
                                fn=update_methods,
         | 
| 265 | 
            -
                                inputs=[methods, dataset_type],
         | 
| 266 | 
            -
                                outputs=[training_ds],
         | 
| 267 | 
            -
                            )
         | 
| 268 | 
            -
                            random_image_output = gr.Image(type="pil", label="Image to Classify")
         | 
| 269 | 
            -
                            with gr.Row():
         | 
| 270 | 
            -
                                generate_button = gr.Button("Sample Random Image")
         | 
| 271 | 
            -
                                classify_button_random = gr.Button("Classify")
         | 
| 272 | 
            -
                        with gr.Column():
         | 
| 273 | 
            -
                            output_label_random = gr.Label(num_top_classes=5)
         | 
| 274 | 
            -
                            download_model = gr.DownloadButton(
         | 
| 275 | 
            -
                                label=f"Download Model: '{label_map[dataset_type.value]}_{label_map[arch_type.value]}_{label_map[training_ds.value]}_{label_map[methods.value]}'",
         | 
| 276 | 
            -
                                value=dataset_models[label_map[dataset_type.value]][
         | 
| 277 | 
            -
                                    f"{label_map[arch_type.value]}_{label_map[training_ds.value]}_{label_map[methods.value]}"
         | 
| 278 | 
            -
                                ][1],
         | 
| 279 | 
            -
                            )
         | 
| 280 | 
            -
                            dataset_type.change(
         | 
| 281 | 
            -
                                fn=downloadModel,
         | 
| 282 | 
            -
                                inputs=[dataset_type, arch_type, methods, training_ds],
         | 
| 283 | 
            -
                                outputs=[download_model],
         | 
| 284 | 
            -
                            )
         | 
| 285 | 
            -
                            arch_type.change(
         | 
| 286 | 
            -
                                fn=downloadModel,
         | 
| 287 | 
            -
                                inputs=[dataset_type, arch_type, methods, training_ds],
         | 
| 288 | 
            -
                                outputs=[download_model],
         | 
| 289 | 
            -
                            )
         | 
| 290 | 
            -
                            methods.change(
         | 
| 291 | 
            -
                                fn=downloadModel,
         | 
| 292 | 
            -
                                inputs=[dataset_type, arch_type, methods, training_ds],
         | 
| 293 | 
            -
                                outputs=[download_model],
         | 
| 294 | 
            -
                            )
         | 
| 295 | 
            -
                            training_ds.change(
         | 
| 296 | 
            -
                                fn=downloadModel,
         | 
| 297 | 
            -
                                inputs=[dataset_type, arch_type, methods, training_ds],
         | 
| 298 | 
            -
                                outputs=[download_model],
         | 
| 299 | 
            -
                            )
         | 
| 300 | 
            -
                            gr.Markdown(
         | 
| 301 | 
            -
                                """
         | 
| 302 | 
            -
            This demo showcases the performance of image classifiers trained on various datasets as part of the project ' | 
| 303 | 
            -
             | 
| 304 | 
            -
            View the models and files used in this demo [here](https://huggingface.co/spaces/czl/generative-augmented-classifiers/tree/main).
         | 
| 305 | 
            -
             | 
| 306 | 
            -
            Usage Instructions & Documentation [here](https://huggingface.co/spaces/czl/generative-augmented-classifiers/blob/main/README.md).
         | 
| 307 | 
            -
                            """
         | 
| 308 | 
            -
                            )
         | 
| 309 | 
            -
             | 
| 310 | 
            -
                    generate_button.click(
         | 
| 311 | 
            -
                        get_random_image,
         | 
| 312 | 
            -
                        inputs=[dataset_type],
         | 
| 313 | 
            -
                        outputs=random_image_output,
         | 
| 314 | 
            -
                    )
         | 
| 315 | 
            -
                    classify_button_random.click(
         | 
| 316 | 
            -
                        classify,
         | 
| 317 | 
            -
                        inputs=[random_image_output, dataset_type, arch_type, methods, training_ds],
         | 
| 318 | 
            -
                        outputs=output_label_random,
         | 
| 319 | 
            -
                    )
         | 
| 320 | 
            -
                demo.launch(show_error=True)
         | 
|  | |
| 1 | 
            +
            import random
         | 
| 2 | 
            +
             | 
| 3 | 
            +
            import gradio as gr
         | 
| 4 | 
            +
            import torch
         | 
| 5 | 
            +
            import torchvision
         | 
| 6 | 
            +
            import torchvision.transforms as transforms
         | 
| 7 | 
            +
            from PIL import Image
         | 
| 8 | 
            +
            from torch import nn
         | 
| 9 | 
            +
            from torchvision.models import mobilenet_v2, resnet18
         | 
| 10 | 
            +
            from torchvision.transforms.functional import InterpolationMode
         | 
| 11 | 
            +
             | 
| 12 | 
            +
            datasets_n_classes = {
         | 
| 13 | 
            +
                "Imagenette": 10,
         | 
| 14 | 
            +
                "Imagewoof": 10,
         | 
| 15 | 
            +
                "Stanford_dogs": 120,
         | 
| 16 | 
            +
            }
         | 
| 17 | 
            +
             | 
| 18 | 
            +
            datasets_model_types = {
         | 
| 19 | 
            +
                "Imagenette": [
         | 
| 20 | 
            +
                    "base_200",
         | 
| 21 | 
            +
                    "base_200+100",
         | 
| 22 | 
            +
                    "synthetic_200",
         | 
| 23 | 
            +
                    "augment_noisy_200",
         | 
| 24 | 
            +
                    "augment_noisy_200+100",
         | 
| 25 | 
            +
                    "augment_clean_200",
         | 
| 26 | 
            +
                ],
         | 
| 27 | 
            +
                "Imagewoof": [
         | 
| 28 | 
            +
                    "base_200",
         | 
| 29 | 
            +
                    "base_200+100",
         | 
| 30 | 
            +
                    "synthetic_200",
         | 
| 31 | 
            +
                    "augment_noisy_200",
         | 
| 32 | 
            +
                    "augment_noisy_200+100",
         | 
| 33 | 
            +
                    "augment_clean_200",
         | 
| 34 | 
            +
                ],
         | 
| 35 | 
            +
                "Stanford_dogs": [
         | 
| 36 | 
            +
                    "base_200",
         | 
| 37 | 
            +
                    "base_200+100",
         | 
| 38 | 
            +
                    "synthetic_200",
         | 
| 39 | 
            +
                    "augment_noisy_200",
         | 
| 40 | 
            +
                    "augment_noisy_200+100",
         | 
| 41 | 
            +
                ],
         | 
| 42 | 
            +
            }
         | 
| 43 | 
            +
             | 
| 44 | 
            +
            model_arch = ["resnet18", "mobilenet_v2"]
         | 
| 45 | 
            +
             | 
| 46 | 
            +
            list_200 = [
         | 
| 47 | 
            +
                "Original",
         | 
| 48 | 
            +
                "Synthetic",
         | 
| 49 | 
            +
                "Original + Synthetic (Noisy)",
         | 
| 50 | 
            +
                "Original + Synthetic (Clean)",
         | 
| 51 | 
            +
            ]
         | 
| 52 | 
            +
             | 
| 53 | 
            +
            list_200_100 = ["Base+100", "AugmentNoisy+100"]
         | 
| 54 | 
            +
             | 
| 55 | 
            +
            methods_map = {
         | 
| 56 | 
            +
                "200 Epochs": list_200,
         | 
| 57 | 
            +
                "200 Epochs on Original + 100": list_200_100,
         | 
| 58 | 
            +
            }
         | 
| 59 | 
            +
             | 
| 60 | 
            +
            label_map = dict()
         | 
| 61 | 
            +
            label_map["Imagenette (10 classes)"] = "Imagenette"
         | 
| 62 | 
            +
            label_map["Imagewoof (10 classes)"] = "Imagewoof"
         | 
| 63 | 
            +
            label_map["Stanford Dogs (120 classes)"] = "Stanford_dogs"
         | 
| 64 | 
            +
            label_map["ResNet-18"] = "resnet18"
         | 
| 65 | 
            +
            label_map["MobileNetV2"] = "mobilenet_v2"
         | 
| 66 | 
            +
            label_map["200 Epochs"] = "200"
         | 
| 67 | 
            +
            label_map["200 Epochs on Original + 100"] = "200+100"
         | 
| 68 | 
            +
            label_map["Original"] = "base"
         | 
| 69 | 
            +
            label_map["Synthetic"] = "synthetic"
         | 
| 70 | 
            +
            label_map["Original + Synthetic (Noisy)"] = "augment_noisy"
         | 
| 71 | 
            +
            label_map["Original + Synthetic (Clean)"] = "augment_clean"
         | 
| 72 | 
            +
            label_map["Base+100"] = "base"
         | 
| 73 | 
            +
            label_map["AugmentNoisy+100"] = "augment_noisy"
         | 
| 74 | 
            +
             | 
| 75 | 
            +
            dataset_models = dict()
         | 
| 76 | 
            +
            for dataset, n_classes in datasets_n_classes.items():
         | 
| 77 | 
            +
                models = dict()
         | 
| 78 | 
            +
                for model_type in datasets_model_types[dataset]:
         | 
| 79 | 
            +
                    for arch in model_arch:
         | 
| 80 | 
            +
                        if arch == "resnet18":
         | 
| 81 | 
            +
                            model = resnet18(weights=None, num_classes=n_classes)
         | 
| 82 | 
            +
                            models[f"{arch}_{model_type}"] = (
         | 
| 83 | 
            +
                                model,
         | 
| 84 | 
            +
                                f"./models/{arch}/{dataset}/{dataset}_{model_type}.pth",
         | 
| 85 | 
            +
                            )
         | 
| 86 | 
            +
                        elif arch == "mobilenet_v2":
         | 
| 87 | 
            +
                            model = mobilenet_v2(weights=None, num_classes=n_classes)
         | 
| 88 | 
            +
                            models[f"{arch}_{model_type}"] = (
         | 
| 89 | 
            +
                                model,
         | 
| 90 | 
            +
                                f"./models/{arch}/{dataset}/{dataset}_{model_type}.pth",
         | 
| 91 | 
            +
                            )
         | 
| 92 | 
            +
                        else:
         | 
| 93 | 
            +
                            raise ValueError(f"Model architecture unavailable: {arch}")
         | 
| 94 | 
            +
                dataset_models[dataset] = models
         | 
| 95 | 
            +
             | 
| 96 | 
            +
             | 
| 97 | 
            +
            def get_random_image(dataset, label_map=label_map) -> Image:
         | 
| 98 | 
            +
                dataset_root = f"./data/{label_map[dataset]}/val"
         | 
| 99 | 
            +
                dataset_img = torchvision.datasets.ImageFolder(
         | 
| 100 | 
            +
                    dataset_root,
         | 
| 101 | 
            +
                    transforms.Compose([transforms.PILToTensor()]),
         | 
| 102 | 
            +
                )
         | 
| 103 | 
            +
                random_idx = random.randint(0, len(dataset_img) - 1)
         | 
| 104 | 
            +
                image, _ = dataset_img[random_idx]
         | 
| 105 | 
            +
                image = transforms.ToPILImage()(image)
         | 
| 106 | 
            +
                image = image.resize(
         | 
| 107 | 
            +
                    (256, 256),
         | 
| 108 | 
            +
                )
         | 
| 109 | 
            +
                return image
         | 
| 110 | 
            +
             | 
| 111 | 
            +
             | 
| 112 | 
            +
            def load_model(model_dict, model_name: str) -> nn.Module:
         | 
| 113 | 
            +
                model_name_lower = model_name.lower()
         | 
| 114 | 
            +
                if model_name_lower in model_dict:
         | 
| 115 | 
            +
                    model = model_dict[model_name_lower][0]
         | 
| 116 | 
            +
                    model_path = model_dict[model_name_lower][1]
         | 
| 117 | 
            +
                    if torch.cuda.is_available():
         | 
| 118 | 
            +
                        checkpoint = torch.load(model_path)
         | 
| 119 | 
            +
                    else:
         | 
| 120 | 
            +
                        checkpoint = torch.load(model_path, map_location="cpu")
         | 
| 121 | 
            +
                    if "setup" in checkpoint:
         | 
| 122 | 
            +
                        if checkpoint["setup"]["distributed"]:
         | 
| 123 | 
            +
                            torch.nn.modules.utils.consume_prefix_in_state_dict_if_present(
         | 
| 124 | 
            +
                                checkpoint["model"], "module."
         | 
| 125 | 
            +
                            )
         | 
| 126 | 
            +
                        model.load_state_dict(checkpoint["model"])
         | 
| 127 | 
            +
                    else:
         | 
| 128 | 
            +
                        model.load_state_dict(checkpoint)
         | 
| 129 | 
            +
                    return model
         | 
| 130 | 
            +
                else:
         | 
| 131 | 
            +
                    raise ValueError(
         | 
| 132 | 
            +
                        f"Model {model_name} is not available for image prediction. Please choose from {[name.capitalize() for name in model_dict.keys()]}."
         | 
| 133 | 
            +
                    )
         | 
| 134 | 
            +
             | 
| 135 | 
            +
             | 
| 136 | 
            +
            def postprocess_default(labels, output) -> dict:
         | 
| 137 | 
            +
                probabilities = nn.functional.softmax(output[0], dim=0)
         | 
| 138 | 
            +
                top_prob, top_catid = torch.topk(probabilities, 5)
         | 
| 139 | 
            +
                confidences = {
         | 
| 140 | 
            +
                    labels[top_catid.tolist()[i]]: top_prob.tolist()[i]
         | 
| 141 | 
            +
                    for i in range(top_prob.shape[0])
         | 
| 142 | 
            +
                }
         | 
| 143 | 
            +
                return confidences
         | 
| 144 | 
            +
             | 
| 145 | 
            +
             | 
| 146 | 
            +
            def classify(
         | 
| 147 | 
            +
                input_image: Image,
         | 
| 148 | 
            +
                dataset_type: str,
         | 
| 149 | 
            +
                arch_type: str,
         | 
| 150 | 
            +
                methods: str,
         | 
| 151 | 
            +
                training_ds: str,
         | 
| 152 | 
            +
                dataset_models=dataset_models,
         | 
| 153 | 
            +
                label_map=label_map,
         | 
| 154 | 
            +
            ) -> dict:
         | 
| 155 | 
            +
                for i in [dataset_type, arch_type, methods, training_ds]:
         | 
| 156 | 
            +
                    if i is None:
         | 
| 157 | 
            +
                        raise ValueError("Please select all options.")
         | 
| 158 | 
            +
                dataset_type = label_map[dataset_type]
         | 
| 159 | 
            +
                arch_type = label_map[arch_type]
         | 
| 160 | 
            +
                methods = label_map[methods]
         | 
| 161 | 
            +
                training_ds = label_map[training_ds]
         | 
| 162 | 
            +
                preprocess_input = transforms.Compose(
         | 
| 163 | 
            +
                    [
         | 
| 164 | 
            +
                        transforms.Resize(
         | 
| 165 | 
            +
                            256,
         | 
| 166 | 
            +
                            interpolation=InterpolationMode.BILINEAR,
         | 
| 167 | 
            +
                            antialias=True,
         | 
| 168 | 
            +
                        ),
         | 
| 169 | 
            +
                        transforms.CenterCrop(224),
         | 
| 170 | 
            +
                        transforms.ToTensor(),
         | 
| 171 | 
            +
                        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
         | 
| 172 | 
            +
                    ]
         | 
| 173 | 
            +
                )
         | 
| 174 | 
            +
                if input_image is None:
         | 
| 175 | 
            +
                    raise ValueError("No image was provided.")
         | 
| 176 | 
            +
                input_tensor: torch.Tensor = preprocess_input(input_image)
         | 
| 177 | 
            +
                input_batch = input_tensor.unsqueeze(0)
         | 
| 178 | 
            +
                model = load_model(
         | 
| 179 | 
            +
                    dataset_models[dataset_type], f"{arch_type}_{training_ds}_{methods}"
         | 
| 180 | 
            +
                )
         | 
| 181 | 
            +
             | 
| 182 | 
            +
                if torch.cuda.is_available():
         | 
| 183 | 
            +
                    input_batch = input_batch.to("cuda")
         | 
| 184 | 
            +
                    model.to("cuda")
         | 
| 185 | 
            +
             | 
| 186 | 
            +
                model.eval()
         | 
| 187 | 
            +
                with torch.inference_mode():
         | 
| 188 | 
            +
                    output: torch.Tensor = model(input_batch)
         | 
| 189 | 
            +
                with open(f"./data/{dataset_type}.txt", "r") as f:
         | 
| 190 | 
            +
                    labels = {i: line.strip() for i, line in enumerate(f.readlines())}
         | 
| 191 | 
            +
                return postprocess_default(labels, output)
         | 
| 192 | 
            +
             | 
| 193 | 
            +
             | 
| 194 | 
            +
            def update_methods(method, ds_type):
         | 
| 195 | 
            +
                if ds_type == "Stanford Dogs (120 classes)" and method == "200 Epochs":
         | 
| 196 | 
            +
                    methods = list_200[:-1]
         | 
| 197 | 
            +
                else:
         | 
| 198 | 
            +
                    methods = methods_map[method]
         | 
| 199 | 
            +
                return gr.update(choices=methods, value=None)
         | 
| 200 | 
            +
             | 
| 201 | 
            +
             | 
| 202 | 
            +
            def downloadModel(
         | 
| 203 | 
            +
                dataset_type, arch_type, methods, training_ds, dataset_models=dataset_models
         | 
| 204 | 
            +
            ):
         | 
| 205 | 
            +
                for i in [dataset_type, arch_type, methods, training_ds]:
         | 
| 206 | 
            +
                    if i is None:
         | 
| 207 | 
            +
                        return gr.update(label="Select Model", value=None)
         | 
| 208 | 
            +
                dataset_type = label_map[dataset_type]
         | 
| 209 | 
            +
                arch_type = label_map[arch_type]
         | 
| 210 | 
            +
                methods = label_map[methods]
         | 
| 211 | 
            +
                training_ds = label_map[training_ds]
         | 
| 212 | 
            +
                if f"{arch_type}_{training_ds}_{methods}" not in dataset_models[dataset_type]:
         | 
| 213 | 
            +
                    return gr.update(label="Select Model", value=None)
         | 
| 214 | 
            +
                model_path = dataset_models[dataset_type][f"{arch_type}_{training_ds}_{methods}"][1]
         | 
| 215 | 
            +
                return gr.update(
         | 
| 216 | 
            +
                    label=f"Download Model: '{dataset_type}_{arch_type}_{training_ds}_{methods}'",
         | 
| 217 | 
            +
                    value=model_path,
         | 
| 218 | 
            +
                )
         | 
| 219 | 
            +
             | 
| 220 | 
            +
             | 
| 221 | 
            +
            if __name__ == "__main__":
         | 
| 222 | 
            +
                with gr.Blocks(title="Generative Augmented Image Classifiers") as demo:
         | 
| 223 | 
            +
                    gr.Markdown(
         | 
| 224 | 
            +
                        """
         | 
| 225 | 
            +
            # Generative Augmented Image Classifiers
         | 
| 226 | 
            +
            Main GitHub Repo: [Generative Data Augmentation](https://github.com/zhulinchng/generative-data-augmentation) | Generative Data Augmentation Demo: [Generative Data Augmented](https://huggingface.co/spaces/czl/generative-data-augmentation-demo).
         | 
| 227 | 
            +
            """
         | 
| 228 | 
            +
                    )
         | 
| 229 | 
            +
                    with gr.Row():
         | 
| 230 | 
            +
                        with gr.Column():
         | 
| 231 | 
            +
                            dataset_type = gr.Radio(
         | 
| 232 | 
            +
                                choices=[
         | 
| 233 | 
            +
                                    "Imagenette (10 classes)",
         | 
| 234 | 
            +
                                    "Imagewoof (10 classes)",
         | 
| 235 | 
            +
                                    "Stanford Dogs (120 classes)",
         | 
| 236 | 
            +
                                ],
         | 
| 237 | 
            +
                                label="Dataset",
         | 
| 238 | 
            +
                                value="Imagenette (10 classes)",
         | 
| 239 | 
            +
                            )
         | 
| 240 | 
            +
                            arch_type = gr.Radio(
         | 
| 241 | 
            +
                                choices=["ResNet-18", "MobileNetV2"],
         | 
| 242 | 
            +
                                label="Model Architecture",
         | 
| 243 | 
            +
                                value="ResNet-18",
         | 
| 244 | 
            +
                                interactive=True,
         | 
| 245 | 
            +
                            )
         | 
| 246 | 
            +
                            methods = gr.Radio(
         | 
| 247 | 
            +
                                label="Methods",
         | 
| 248 | 
            +
                                choices=["200 Epochs", "200 Epochs on Original + 100"],
         | 
| 249 | 
            +
                                interactive=True,
         | 
| 250 | 
            +
                                value="200 Epochs",
         | 
| 251 | 
            +
                            )
         | 
| 252 | 
            +
                            training_ds = gr.Radio(
         | 
| 253 | 
            +
                                label="Training Dataset",
         | 
| 254 | 
            +
                                choices=methods_map["200 Epochs"],
         | 
| 255 | 
            +
                                interactive=True,
         | 
| 256 | 
            +
                                value="Original",
         | 
| 257 | 
            +
                            )
         | 
| 258 | 
            +
                            dataset_type.change(
         | 
| 259 | 
            +
                                fn=update_methods,
         | 
| 260 | 
            +
                                inputs=[methods, dataset_type],
         | 
| 261 | 
            +
                                outputs=[training_ds],
         | 
| 262 | 
            +
                            )
         | 
| 263 | 
            +
                            methods.change(
         | 
| 264 | 
            +
                                fn=update_methods,
         | 
| 265 | 
            +
                                inputs=[methods, dataset_type],
         | 
| 266 | 
            +
                                outputs=[training_ds],
         | 
| 267 | 
            +
                            )
         | 
| 268 | 
            +
                            random_image_output = gr.Image(type="pil", label="Image to Classify")
         | 
| 269 | 
            +
                            with gr.Row():
         | 
| 270 | 
            +
                                generate_button = gr.Button("Sample Random Image")
         | 
| 271 | 
            +
                                classify_button_random = gr.Button("Classify")
         | 
| 272 | 
            +
                        with gr.Column():
         | 
| 273 | 
            +
                            output_label_random = gr.Label(num_top_classes=5)
         | 
| 274 | 
            +
                            download_model = gr.DownloadButton(
         | 
| 275 | 
            +
                                label=f"Download Model: '{label_map[dataset_type.value]}_{label_map[arch_type.value]}_{label_map[training_ds.value]}_{label_map[methods.value]}'",
         | 
| 276 | 
            +
                                value=dataset_models[label_map[dataset_type.value]][
         | 
| 277 | 
            +
                                    f"{label_map[arch_type.value]}_{label_map[training_ds.value]}_{label_map[methods.value]}"
         | 
| 278 | 
            +
                                ][1],
         | 
| 279 | 
            +
                            )
         | 
| 280 | 
            +
                            dataset_type.change(
         | 
| 281 | 
            +
                                fn=downloadModel,
         | 
| 282 | 
            +
                                inputs=[dataset_type, arch_type, methods, training_ds],
         | 
| 283 | 
            +
                                outputs=[download_model],
         | 
| 284 | 
            +
                            )
         | 
| 285 | 
            +
                            arch_type.change(
         | 
| 286 | 
            +
                                fn=downloadModel,
         | 
| 287 | 
            +
                                inputs=[dataset_type, arch_type, methods, training_ds],
         | 
| 288 | 
            +
                                outputs=[download_model],
         | 
| 289 | 
            +
                            )
         | 
| 290 | 
            +
                            methods.change(
         | 
| 291 | 
            +
                                fn=downloadModel,
         | 
| 292 | 
            +
                                inputs=[dataset_type, arch_type, methods, training_ds],
         | 
| 293 | 
            +
                                outputs=[download_model],
         | 
| 294 | 
            +
                            )
         | 
| 295 | 
            +
                            training_ds.change(
         | 
| 296 | 
            +
                                fn=downloadModel,
         | 
| 297 | 
            +
                                inputs=[dataset_type, arch_type, methods, training_ds],
         | 
| 298 | 
            +
                                outputs=[download_model],
         | 
| 299 | 
            +
                            )
         | 
| 300 | 
            +
                            gr.Markdown(
         | 
| 301 | 
            +
                                """
         | 
| 302 | 
            +
            This demo showcases the performance of image classifiers trained on various datasets as part of the project 'Improving Fine-Grained Image Classification Using Diffusion-Based Generated Synthetic Images' dissertation.
         | 
| 303 | 
            +
             | 
| 304 | 
            +
            View the models and files used in this demo [here](https://huggingface.co/spaces/czl/generative-augmented-classifiers/tree/main).
         | 
| 305 | 
            +
             | 
| 306 | 
            +
            Usage Instructions & Documentation [here](https://huggingface.co/spaces/czl/generative-augmented-classifiers/blob/main/README.md).
         | 
| 307 | 
            +
                            """
         | 
| 308 | 
            +
                            )
         | 
| 309 | 
            +
             | 
| 310 | 
            +
                    generate_button.click(
         | 
| 311 | 
            +
                        get_random_image,
         | 
| 312 | 
            +
                        inputs=[dataset_type],
         | 
| 313 | 
            +
                        outputs=random_image_output,
         | 
| 314 | 
            +
                    )
         | 
| 315 | 
            +
                    classify_button_random.click(
         | 
| 316 | 
            +
                        classify,
         | 
| 317 | 
            +
                        inputs=[random_image_output, dataset_type, arch_type, methods, training_ds],
         | 
| 318 | 
            +
                        outputs=output_label_random,
         | 
| 319 | 
            +
                    )
         | 
| 320 | 
            +
                demo.launch(show_error=True)
         | 
