Skip to content

Commit

Permalink
Always use local resource (#2284)
Browse files Browse the repository at this point in the history
Summary: Pull Request resolved: #2284

Differential Revision: D54609685
  • Loading branch information
kirklandsign authored and facebook-github-bot committed Mar 7, 2024
1 parent 5916639 commit cf929d0
Showing 1 changed file with 2 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,11 @@

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.pytorch.executorch.LlamaCallback;
import org.pytorch.executorch.LlamaModule;

Expand All @@ -34,42 +28,13 @@ public class MainActivity extends Activity implements Runnable, LlamaCallback {
private LlamaModule mModule = null;
private Message mResultMessage = null;

private static String assetFilePath(Context context, String assetName) throws IOException {
File file = new File(context.getFilesDir(), assetName);
if (file.exists() && file.length() > 0) {
return file.getAbsolutePath();
}

try (InputStream is = context.getAssets().open(assetName)) {
try (OutputStream os = new FileOutputStream(file)) {
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
os.flush();
}
return file.getAbsolutePath();
}
}

@Override
public void onResult(String result) {
System.out.println("onResult: " + result);
mResultMessage.appendText(result);
run();
}

private void setModel(String modelPath, String tokenizerPath) {
try {
String model = MainActivity.assetFilePath(getApplicationContext(), modelPath);
String tokenizer = MainActivity.assetFilePath(getApplicationContext(), tokenizerPath);
mModule = new LlamaModule(model, tokenizer, 0.8f);
} catch (IOException e) {
finish();
}
}

private void setLocalModel(String modelPath, String tokenizerPath) {
mModule = new LlamaModule(modelPath, tokenizerPath, 0.8f);
}
Expand All @@ -84,7 +49,7 @@ private void modelDialog() {
public void onClick(android.content.DialogInterface dialog, int item) {
switch (item) {
case 0:
setModel("stories110M.pte", "tokenizer.bin");
setLocalModel("/data/local/tmp/stories110M.pte", "/data/local/tmp/tokenizer.bin");
break;
case 1:
setLocalModel("/data/local/tmp/language.pte", "/data/local/tmp/language.bin");
Expand Down Expand Up @@ -141,7 +106,7 @@ public void run() {
modelDialog();
});

setModel("stories110M.pte", "tokenizer.bin");
setLocalModel("/data/local/tmp/stories110M.pte", "/data/local/tmp/tokenizer.bin");
}

@Override
Expand Down

0 comments on commit cf929d0

Please sign in to comment.