[go: nahoru, domu]

Skip to content
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

[tfjs-react-native] Fixed model loading after applying CodePush update #3703

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

iAmGhost
Copy link
@iAmGhost iAmGhost commented Jul 31, 2020

react-native-code-push allows update js bundle and assets without publishing new version of app package.

After applying CodePush update, Asset returns uri in file:// URL form instead of file path. which is okay in most use but since tfjs-react-native uses react-native-fs for loading bundled weights, converting URL to path must be done.

This pull request implements file URL detection and converting for solving this problem.

and here's quick workaround for before this request accepted:

import * as tf from '@tensorflow/tfjs';
import {bundleResourceIO} from '@tensorflow/tfjs-react-native';
import {Image} from 'react-native';

const myModelJson = require('../assets/my_model.json');
const myModelWeights = require('../assets/my_model_weights.bin');

class LocalFileHandler {
  constructor(modelJson, modelWeightsId) {
    this.modelJson = modelJson;
    this.modelWeightsId = modelWeightsId;
  }

  async load() {
    const localFilePath = unescape(
      Image.resolveAssetSource(this.modelWeightsId).uri.substr(
        'file://'.length,
      ),
    );
    const base64Weights = await RNFS.readFile(localFilePath, 'base64');
    const weightData = tf.util.encodeString(base64Weights, 'base64').buffer;

    const modelArtifacts = Object.assign({}, this.modelJson);
    modelArtifacts.weightSpecs = this.modelJson.weightsManifest[0].weights;
    delete modelArtifacts.weightManifest;
    modelArtifacts.weightData = weightData;
    return modelArtifacts;
  }
}

let resourceIO = bundleResourceIO(
  myModelJson,
  myModelWeights,
);

if (
  Image.resolveAssetSource(myModelWeights).uri.match('^file://')
) {
  resourceIO = new LocalFileHandler(
    myModelJson,
    myModelWeights,
  );
}

const model = await tf.loadGraphModel(resourceIO);

This change is Reviewable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants