@@ -0,0 +1,2267 @@
+%22%22%22%0AA simple Python API for loading Keras models from MongoDB run artifact stored%0Aby the Sacred library.%0A%0AUsage:%0A%0Arun_id = '5843062c4e60f9a60c9db41f'%0Amodel = get_model(get_run(run_id))%0A%22%22%22%0A%0Afrom bson.objectid import ObjectId%0Aimport keras%0Aimport pymongo%0Afrom tempfile import TemporaryDirectory%0A%0Amongo_client = pymongo.MongoClient()%0Adb = mongo_client%5B'sacred'%5D%0A%0Adef list_runs(exp_name=None):%0A    return db%5B'default.runs'%5D.find(%7B%7D, %7B'_id': True%7D)%0A%0Adef list_experiment_runs(exp_name):%0A    return db%5B'default.runs'%5D.find(%0A        %7B'experiment.name': exp_name%7D,%0A        %7B'_id': True%7D)%0A%0Adef list_experiments():%0A    return db%5B'default.runs'%5D.distinct('experiment.name')%0A%0Adef get_run(run_id):%0A    runs = db%5B'default.runs'%5D%0A    if isinstance(run_id, str):%0A        run_id = ObjectId(run_id)%0A    return runs.find_one(run_id)%0A%0Adef get_file_chunks(file_id):%0A    chunks = db%5B'default.chunks'%5D%0A    for chunk in chunks.find(%7B'files_id': file_id%7D) %5C%0A        .sort(%5B('n', pymongo.ASCENDING)%5D):%0A        yield chunk%5B'data'%5D%0A%0Adef find_model_artifact(run, suffix='model.h5'):%0A    files = db%5B'default.files'%5D%0A    for artifact_id in run%5B'artifacts'%5D:%0A        artifact = files.find_one(artifact_id)%0A        if artifact%5B'filename'%5D.endswith(suffix):%0A            return artifact%0A%0A# We stored the model as a run artifact. The artifact file is stored in%0A# multiple chunks which we need to put together.%0Adef model_from_chunks(model_chunks):%0A    # Since h5py doesn't allow reading from in-memory file-like objects,%0A    # let's store it to a temporary file.%0A    # http://stackoverflow.com/questions/16654251/can-h5py-load-a-file-from-a-byte-array-in-memory%0A    # We use TemporaryDirectory instead of NamedTemporaryFile since after%0A    # closing such file it gets deleted before Keras can load it.%0A    with TemporaryDirectory() as temp_dir:%0A        model_file = temp_dir + '/model.h5'%0A        with open(model_file, 'wb') as f:%0A            for chunk_data in model_chunks:%0A                f.write(chunk_data)%0A        return keras.models.load_model(model_file)%0A%0Adef get_model(run):%0A    model_artifact = find_model_artifact(run)%0A    print('Loading model:', model_artifact%5B'filename'%5D)%0A    model_chunks = get_file_chunks(model_artifact%5B'_id'%5D)%0A    model = model_from_chunks(model_chunks)%0A%0A    return model%0A

Add a script to load a Keras model from MongoDB where it was stored by Sacred.