Skip to content

Add Ml shared preferences for custom model storage #2104

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Oct 29, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ dependencies {
implementation project(':firebase-components')

implementation 'com.google.android.gms:play-services-tasks:17.2.0'
implementation 'javax.inject:javax.inject:1'

compileOnly "com.google.auto.value:auto-value-annotations:1.6.6"
annotationProcessor "com.google.auto.value:auto-value:1.6.5"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.gms.common.internal.Objects;
import java.io.File;

/**
Expand All @@ -28,7 +29,44 @@ public class CustomModel {
private final long downloadId;
private final long fileSize;
private final String modelHash;
private final String localFilePath = "";
private final String localFilePath;

/**
* Use when creating a custom model while the initial download is still in progress.
*
* @param name - model name
* @param downloadId - Android Download Manger - download id
* @param fileSize - model file size
* @param modelHash - model hash size
* @hide
*/
public CustomModel(
@NonNull String name, long downloadId, long fileSize, @NonNull String modelHash) {
this(name, downloadId, fileSize, modelHash, "");
}

/**
* Use when creating a custom model while the initial download is still in progress.
*
* @param name - model name
* @param downloadId - Android Download Manger - download id
* @param fileSize - model file size
* @param modelHash - model hash size
* @param localFilePath - location of the current file
* @hide
*/
public CustomModel(
@NonNull String name,
long downloadId,
long fileSize,
@NonNull String modelHash,
@NonNull String localFilePath) {
this.modelHash = modelHash;
this.name = name;
this.fileSize = fileSize;
this.downloadId = downloadId;
this.localFilePath = localFilePath;
}

@NonNull
public String getName() {
Expand Down Expand Up @@ -76,18 +114,36 @@ public long getDownloadId() {
return downloadId;
}

@Override
public boolean equals(Object o) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Override hashCode when overriding equals (Item 11 in Effective Java)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks - added.

if (o == this) {
return true;
}

if (!(o instanceof CustomModel)) {
return false;
}

CustomModel other = (CustomModel) o;

return Objects.equal(name, other.name)
&& Objects.equal(modelHash, other.modelHash)
&& Objects.equal(fileSize, other.fileSize)
&& Objects.equal(localFilePath, other.localFilePath)
&& Objects.equal(downloadId, other.downloadId);
}

@Override
public int hashCode() {
return Objects.hashCode(name, modelHash, fileSize, localFilePath, downloadId);
}

/**
* Use when creating a custom model while the initial download is still in progress.
*
* @param name - model name
* @param downloadId - Android Download Manger - download id
* @param fileSize - model file size
* @param modelHash - model hash size
* @return the model file path
* @hide
*/
CustomModel(String name, long downloadId, long fileSize, String modelHash) {
this.modelHash = modelHash;
this.name = name;
this.fileSize = fileSize;
this.downloadId = downloadId;
@NonNull
public String getLocalFilePath() {
return localFilePath;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package com.google.firebase.ml.modeldownloader;

import androidx.annotation.NonNull;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.components.Component;
import com.google.firebase.components.ComponentRegistrar;
Expand All @@ -36,6 +37,7 @@ public class FirebaseModelDownloaderRegistrar implements ComponentRegistrar {
public List<Component<?>> getComponents() {
return Arrays.asList(
Component.builder(FirebaseModelDownloader.class)
.add(Dependency.required(FirebaseApp.class))
.add(Dependency.required(FirebaseOptions.class))
.factory(c -> new FirebaseModelDownloader(c.get(FirebaseOptions.class)))
.build(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.ml.modeldownloader.internal;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import com.google.firebase.FirebaseApp;
import com.google.firebase.ml.modeldownloader.CustomModel;

/** @hide */
public class SharedPreferencesUtil {

@VisibleForTesting
static final String PREFERENCES_PACKAGE_NAME = "com.google.firebase.ml.modelDownloader";

// local model details
private static final String LOCAL_MODEL_HASH_PATTERN = "current_model_hash_%s_%s";
private static final String LOCAL_MODEL_FILE_PATH_PATTERN = "current_model_path_%s_%s";
private static final String LOCAL_MODEL_FILE_SIZE_PATTERN = "current_model_size_%s_%s";
// details about model during download.
private static final String DOWNLOADING_MODEL_HASH_PATTERN = "downloading_model_hash_%s_%s";
private static final String DOWNLOADING_MODEL_SIZE_PATTERN = "downloading_model_size_%s_%s";
private static final String DOWNLOADING_MODEL_ID_PATTERN = "downloading_model_id_%s_%s";
private static final String DOWNLOAD_BEGIN_TIME_MS_PATTERN = "downloading_begin_time_%s_%s";

private final String persistenceKey;
private final FirebaseApp firebaseApp;

public SharedPreferencesUtil(FirebaseApp firebaseApp) {
this.firebaseApp = firebaseApp;
this.persistenceKey = firebaseApp.getPersistenceKey();
}

/**
* Returns the Custom Model details currently associated with this model. If a fully downloaded
* model is present - this returns the details of that model, including local file path. If an
* update of an existing model is in progress, the local model plus the download id for the new
* upload is returned. To get only details related to the downloading model use {@link
* #getDownloadingCustomModelDetails}. If this is the initial download of a local file - the
* downloading model details are returned.
*
* @param modelName - name of the model
* @return current version of the Custom Model
*/
@Nullable
public synchronized CustomModel getCustomModelDetails(@NonNull String modelName) {
String modelHash =
getSharedPreferences()
.getString(String.format(LOCAL_MODEL_HASH_PATTERN, persistenceKey, modelName), null);

if (modelHash == null || modelHash.isEmpty()) {
// no model downloaded - check if model is being downloaded.
return getDownloadingCustomModelDetails(modelName);
}

String filePath =
getSharedPreferences()
.getString(String.format(LOCAL_MODEL_FILE_PATH_PATTERN, persistenceKey, modelName), "");

long fileSize =
getSharedPreferences()
.getLong(String.format(LOCAL_MODEL_FILE_SIZE_PATTERN, persistenceKey, modelName), 0);

// if no-zero - local model is present and new model being downloaded
long id =
getSharedPreferences()
.getLong(String.format(DOWNLOADING_MODEL_ID_PATTERN, persistenceKey, modelName), 0);

return new CustomModel(modelName, id, fileSize, modelHash, filePath);
}

/**
* Returns the Custom Model details associated with this version of this model currently being
* downloaded. If no download is in progress return null. Contains no information about local
* model, only download status.
*
* @param modelName name of the model
* @return Download version of CustomModel
*/
@Nullable
public synchronized CustomModel getDownloadingCustomModelDetails(@NonNull String modelName) {
String modelHash =
getSharedPreferences()
.getString(
String.format(DOWNLOADING_MODEL_HASH_PATTERN, persistenceKey, modelName), null);

if (modelHash == null || modelHash.isEmpty()) {
// no model hash means no download in progress
return null;
}

long fileSize =
getSharedPreferences()
.getLong(String.format(DOWNLOADING_MODEL_SIZE_PATTERN, persistenceKey, modelName), 0);

long id =
getSharedPreferences()
.getLong(String.format(DOWNLOADING_MODEL_ID_PATTERN, persistenceKey, modelName), 0);

return new CustomModel(modelName, id, fileSize, modelHash);
}

/**
* The information about the new custom model download that need to be stored.
*
* @param customModel custom model details to be stored.
*/
public synchronized void setDownloadingCustomModelDetails(@NonNull CustomModel customModel) {
String modelName = customModel.getName();
String modelHash = customModel.getModelHash();
long downloadId = customModel.getDownloadId();
long modelSize = customModel.getSize();
getSharedPreferences()
.edit()
.putString(
String.format(DOWNLOADING_MODEL_HASH_PATTERN, persistenceKey, modelName), modelHash)
.putLong(
String.format(DOWNLOADING_MODEL_SIZE_PATTERN, persistenceKey, modelName), modelSize)
.putLong(String.format(DOWNLOADING_MODEL_ID_PATTERN, persistenceKey, modelName), downloadId)
// The following assumes the download will finish before the system reboots.
// If not, the download duration won't be correct, which isn't critical.
.putLong(
String.format(DOWNLOAD_BEGIN_TIME_MS_PATTERN, persistenceKey, modelName),
SystemClock.elapsedRealtime())
.commit();
}

/**
* The information about a completed custom model download. Updates the local model information
* and clears the download details associated with this model.
*
* @param customModel custom model details to be stored.
*/
public synchronized void setUploadedCustomModelDetails(@NonNull CustomModel customModel)
throws IllegalArgumentException {
Long id = customModel.getDownloadId();
// only call when download is completed and download id is reset to 0;
if (!id.equals(0L)) {
throw new IllegalArgumentException("Only call when Custom model has completed download.");
}
Editor editor = getSharedPreferences().edit();
clearDownloadingModelDetails(editor, customModel.getName());

String modelName = customModel.getName();
String hash = customModel.getModelHash();
long size = customModel.getSize();
String filePath = customModel.getLocalFilePath();
editor
.putString(String.format(LOCAL_MODEL_HASH_PATTERN, persistenceKey, modelName), hash)
.putLong(String.format(LOCAL_MODEL_FILE_SIZE_PATTERN, persistenceKey, modelName), size)
.putString(
String.format(LOCAL_MODEL_FILE_PATH_PATTERN, persistenceKey, modelName), filePath)
.commit();
}

/**
* Clears all stored data related to a local custom model, including download details.
*
* @param modelName - name of model
*/
public synchronized void clearModelDetails(@NonNull String modelName, boolean cleanUpModelFile) {
if (cleanUpModelFile) {
// TODO(annz) - add code to remove model files from device
}
Editor editor = getSharedPreferences().edit();

clearDownloadingModelDetails(editor, modelName);

editor
.remove(String.format(LOCAL_MODEL_FILE_PATH_PATTERN, persistenceKey, modelName))
.remove(String.format(LOCAL_MODEL_FILE_SIZE_PATTERN, persistenceKey, modelName))
.remove(String.format(LOCAL_MODEL_HASH_PATTERN, persistenceKey, modelName))
.commit();
}

/**
* Clears all stored data related to a custom model download.
*
* @param modelName - name of model
*/
@VisibleForTesting
synchronized void clearDownloadingModelDetails(Editor editor, @NonNull String modelName) {
editor
.remove(String.format(DOWNLOADING_MODEL_ID_PATTERN, persistenceKey, modelName))
.remove(String.format(DOWNLOADING_MODEL_HASH_PATTERN, persistenceKey, modelName))
.remove(String.format(DOWNLOADING_MODEL_SIZE_PATTERN, persistenceKey, modelName))
.remove(String.format(DOWNLOAD_BEGIN_TIME_MS_PATTERN, persistenceKey, modelName))
.apply();
}

@VisibleForTesting
SharedPreferences getSharedPreferences() {
return firebaseApp
.getApplicationContext()
.getSharedPreferences(PREFERENCES_PACKAGE_NAME, Context.MODE_PRIVATE);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
package com.google.firebase.ml.modeldownloader;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.junit.runner.RunWith;
Expand Down Expand Up @@ -52,4 +55,21 @@ public void customModel_getDownloadId() {
public void customModel_getFile_downloadIncomplete() {
assertNull(CUSTOM_MODEL.getFile());
}

@Test
public void customModel_equals() {
assertTrue(CUSTOM_MODEL.equals(new CustomModel(MODEL_NAME, 0, 100, MODEL_HASH)));
assertFalse(CUSTOM_MODEL.equals(new CustomModel(MODEL_NAME, 0, 101, MODEL_HASH)));
assertFalse(CUSTOM_MODEL.equals(new CustomModel(MODEL_NAME, 101, 100, MODEL_HASH)));
}

@Test
public void customModel_hashCode() {
assertEquals(
CUSTOM_MODEL.hashCode(), new CustomModel(MODEL_NAME, 0, 100, MODEL_HASH).hashCode());
assertNotEquals(
CUSTOM_MODEL.hashCode(), new CustomModel(MODEL_NAME, 0, 101, MODEL_HASH).hashCode());
assertNotEquals(
CUSTOM_MODEL.hashCode(), new CustomModel(MODEL_NAME, 101, 100, MODEL_HASH).hashCode());
}
}
Loading