|
| 1 | +import hashlib |
| 2 | +import os |
| 3 | +from typing import Dict |
| 4 | +from tensorflow import keras |
| 5 | + |
| 6 | + |
| 7 | +class ModelUtility: |
| 8 | + def __init__(self, config: Dict[str, str]): |
| 9 | + """ |
| 10 | + Instaniates a new object using data needed to load in the model. |
| 11 | +
|
| 12 | + Args: |
| 13 | + config(dict): contains the following fields of interest: |
| 14 | + base_model_url(str): the base url where the files are located |
| 15 | + model_file_paths(list): collection of all the files needed to |
| 16 | + eventually load the model |
| 17 | + model_sha256(str): the supposed hash of one of the files |
| 18 | + we need to download. Checked against the |
| 19 | + one we may already have in the codebase. |
| 20 | + """ |
| 21 | + self.url = config["base_model_url"] |
| 22 | + self.file_paths = config["model_file_paths"] |
| 23 | + self.file_sha256 = None |
| 24 | + if config["model_sha256"] is not None: |
| 25 | + self.file_sha256 = config["model_sha256"] |
| 26 | + |
| 27 | + @classmethod |
| 28 | + def reconstruct_model(cls, config): |
| 29 | + '''Make a new instance, and load in the model straightaway.''' |
| 30 | + model_utility = cls(config) |
| 31 | + # detect save format |
| 32 | + save_format = 'composite' |
| 33 | + if config["model_file_paths"] and len(config["model_file_paths"]) == 1: |
| 34 | + save_format = 'h5' |
| 35 | + # load the model |
| 36 | + return model_utility.load_model(save_format) |
| 37 | + |
| 38 | + def get_hash(self, filename): |
| 39 | + """ |
| 40 | + Computes the SHA256 hash of a given file. |
| 41 | +
|
| 42 | + This can then be used to ensure the model file(s) downloaded |
| 43 | + in this codebase are not corrupted. |
| 44 | +
|
| 45 | + Args: |
| 46 | + filename(str): the name of the file |
| 47 | +
|
| 48 | + Returns: |
| 49 | + bytes-like object |
| 50 | + """ |
| 51 | + sha256_hash = hashlib.sha256() |
| 52 | + with open(filename, "rb") as f: |
| 53 | + for byte_block in iter(lambda: f.read(4096), b""): |
| 54 | + sha256_hash.update(byte_block) |
| 55 | + |
| 56 | + return sha256_hash.hexdigest() |
| 57 | + |
| 58 | + def download_model(self): |
| 59 | + """ |
| 60 | + Downloads the model files in memory. |
| 61 | +
|
| 62 | + This will first check if the files are already present, |
| 63 | + and not corrupted, before downloading from the address |
| 64 | + specified in config.yaml. |
| 65 | +
|
| 66 | + Returns: |
| 67 | + None |
| 68 | + """ |
| 69 | + # Download only the model files that are needed |
| 70 | + for model_file_path in self.file_paths: |
| 71 | + if os.path.exists(model_file_path): |
| 72 | + if self.get_hash(model_file_path) == self.file_sha256: |
| 73 | + print(f"File already exists: {model_file_path}") |
| 74 | + else: # need to download the model |
| 75 | + model_file_url = f"{self.url}/{model_file_path}" |
| 76 | + keras.utils.get_file( |
| 77 | + origin=model_file_url, |
| 78 | + fname=model_file_path, |
| 79 | + cache_dir=".", |
| 80 | + cache_subdir="./model", |
| 81 | + ) |
| 82 | + |
| 83 | + def load_model(self, format="composite"): |
| 84 | + """ |
| 85 | + Model reconstruction. |
| 86 | +
|
| 87 | + This will first load the model in memory using the given files |
| 88 | + and save format |
| 89 | +
|
| 90 | + Args: |
| 91 | + format(str): currently this only supports 'composite' |
| 92 | + (which is for when the model is saved using a H5 + JSON) |
| 93 | + or 'h5' as the save format of the model. |
| 94 | +
|
| 95 | + Returns: |
| 96 | + keras.Model object |
| 97 | + """ |
| 98 | + |
| 99 | + def _model_from_composite_format(): |
| 100 | + """Specific to using H5 + JSON as the save format""" |
| 101 | + params_file, layers_file = self.file_paths |
| 102 | + # load the model in memory |
| 103 | + with open(f"./model/{layers_file}") as f: |
| 104 | + model = keras.models.model_from_json(f.read()) # build the layers |
| 105 | + model.load_weights(f"./model/{params_file}") # load weights + biases |
| 106 | + return model |
| 107 | + |
| 108 | + def _model_from_h5(): |
| 109 | + """Specific to using a single Hadoop(H5) file""" |
| 110 | + params_file = self.file_paths[0] |
| 111 | + return keras.models.load_model(params_file) |
| 112 | + |
| 113 | + # First download the model, if needed |
| 114 | + self.download_model() |
| 115 | + # load the model in memory |
| 116 | + if format == "composite": |
| 117 | + return _model_from_composite_format() |
| 118 | + else: # assuming a single H5 |
| 119 | + return _model_from_h5() |
0 commit comments