|
| 1 | +import argparse |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import yaml |
| 5 | +from tensorflow.keras.models import load_model |
| 6 | + |
| 7 | +from fire_classifier.preprocessing_utilities import ( |
| 8 | + read_img_from_path, |
| 9 | + read_from_file, |
| 10 | +) |
| 11 | +from fire_classifier.utils import download_model |
| 12 | + |
| 13 | + |
| 14 | +class ImagePredictor: |
| 15 | + def __init__(self, model_path, resize_size, targets): |
| 16 | + self.model_path = model_path |
| 17 | + self.model = load_model(self.model_path) |
| 18 | + self.resize_size = resize_size |
| 19 | + self.targets = targets |
| 20 | + |
| 21 | + @classmethod |
| 22 | + def init_from_config_path(cls, config_path): |
| 23 | + with open(config_path, "r") as f: |
| 24 | + config = yaml.load(f, yaml.SafeLoader) |
| 25 | + predictor = cls( |
| 26 | + model_path=config["model_path"], |
| 27 | + resize_size=config["resize_shape"], |
| 28 | + targets=config["targets"], |
| 29 | + ) |
| 30 | + return predictor |
| 31 | + |
| 32 | + @classmethod |
| 33 | + def init_from_config_url(cls, config_path): |
| 34 | + with open(config_path, "r") as f: |
| 35 | + config = yaml.load(f, yaml.SafeLoader) |
| 36 | + |
| 37 | + download_model( |
| 38 | + config["model_url"], config["model_path"], config["model_sha256"] |
| 39 | + ) |
| 40 | + |
| 41 | + return cls.init_from_config_path(config_path) |
| 42 | + |
| 43 | + def predict_from_array(self, arr): |
| 44 | + pred = self.model.predict(arr[np.newaxis, ...]).ravel().tolist() |
| 45 | + pred = [round(x, 3) for x in pred] |
| 46 | + return {k: v for k, v in zip(self.targets, pred)} |
| 47 | + |
| 48 | + def predict_from_path(self, path): |
| 49 | + arr = read_img_from_path(path) |
| 50 | + return self.predict_from_array(arr) |
| 51 | + |
| 52 | + def predict_from_file(self, file_object): |
| 53 | + arr = read_from_file(file_object) |
| 54 | + return self.predict_from_array(arr) |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + """ |
| 59 | + python predictor.py --predictor_config "../example/predictor_config.yaml" |
| 60 | +
|
| 61 | + """ |
| 62 | + parser = argparse.ArgumentParser() |
| 63 | + parser.add_argument( |
| 64 | + "--predictor_config_path", |
| 65 | + help="predictor_config_path", |
| 66 | + default="../example/predictor_config.yaml", |
| 67 | + ) |
| 68 | + |
| 69 | + args = parser.parse_args() |
| 70 | + |
| 71 | + predictor_config_path = args.predictor_config_path |
| 72 | + |
| 73 | + predictor = ImagePredictor.init_from_config_path(predictor_config_path) |
0 commit comments