Skip to content

Commit 5afb267

Browse files
committed
finished code
1 parent ea2ae94 commit 5afb267

File tree

11 files changed

+352
-28
lines changed

11 files changed

+352
-28
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package io.fynn.torch_mobile;
2+
3+
public class Convert {
4+
5+
public static String dtypeAsPrimitive(String dtype){
6+
switch (dtype.toLowerCase()){
7+
case "float32":
8+
return "Float";
9+
case "float64":
10+
return "Double";
11+
case "int32":
12+
return "Integer";
13+
case "int64":
14+
return "Long";
15+
case "int8":
16+
return "Byte";
17+
case "uint8":
18+
return "Byte";
19+
default:
20+
return null;
21+
}
22+
}
23+
24+
public static long[] toPrimitives(Integer[] objects){
25+
long[] primitives = new long[objects.length];
26+
for(int i = 0; i < objects.length; i++){
27+
primitives[i] = objects[i].longValue();
28+
}
29+
return primitives;
30+
}
31+
32+
public static byte[] toBytePrimitives(Double[] objects){
33+
byte[] primitives = new byte[objects.length];
34+
for(int i = 0; i < objects.length; i++){
35+
primitives[i] = objects[i].byteValue();
36+
}
37+
return primitives;
38+
}
39+
40+
public static float[] toFloatPrimitives(Double[] objects){
41+
float[] primitives = new float[objects.length];
42+
for(int i = 0; i < objects.length; i++){
43+
primitives[i] = objects[i].floatValue();
44+
}
45+
return primitives;
46+
}
47+
48+
public static double[] toDoublePrimitives(Double[] objects){
49+
double[] primitives = new double[objects.length];
50+
for(int i = 0; i < objects.length; i++){
51+
primitives[i] = objects[i].doubleValue();
52+
}
53+
return primitives;
54+
}
55+
56+
public static long[] toLongPrimitives(Double[] objects){
57+
long[] primitives = new long[objects.length];
58+
for(int i = 0; i < objects.length; i++){
59+
primitives[i] = objects[i].longValue();
60+
}
61+
return primitives;
62+
}
63+
64+
public static int[] toIntegerPrimitives(Double[] objects){
65+
int[] primitives = new int[objects.length];
66+
for(int i = 0; i < objects.length; i++){
67+
primitives[i] = objects[i].intValue();
68+
}
69+
return primitives;
70+
}
71+
}

android/src/main/java/io/fynn/torch_mobile/TorchMobilePlugin.java

+135-11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package io.fynn.torch_mobile;
22

3+
import android.graphics.Bitmap;
4+
import android.graphics.BitmapFactory;
35
import android.util.Log;
46

57
import androidx.annotation.NonNull;
@@ -10,17 +12,19 @@
1012
import io.flutter.plugin.common.MethodChannel.Result;
1113
import io.flutter.plugin.common.PluginRegistry.Registrar;
1214

15+
import org.pytorch.DType;
1316
import org.pytorch.IValue;
1417
import org.pytorch.Module;
1518
import org.pytorch.Tensor;
1619
import org.pytorch.torchvision.TensorImageUtils;
1720

1821
import java.util.ArrayList;
1922
import java.util.Arrays;
23+
import java.util.HashMap;
2024
import java.util.List;
2125

2226
/** TorchMobilePlugin */
23-
public class TorchMobilePlugin implements FlutterPlugin, MethodCallHandler {
27+
public class TorchMobilePlugin<T> implements FlutterPlugin, MethodCallHandler {
2428

2529
ArrayList<Module> modules = new ArrayList<>();
2630

@@ -50,31 +54,151 @@ public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
5054
}
5155
break;
5256
case "predict":
53-
Module module;
57+
Module module = null;
58+
Integer[] shape = null;
59+
Double[] data = null;
60+
DType dtype = null;
61+
5462
try{
5563
int index = call.argument("index");
5664
module = modules.get(index);
5765

58-
ArrayList<Long> shapeList = call.argument("shape");
59-
Long[] shape = shapeList.toArray(new Long[shapeList.size()]);
60-
Tensor.fromBlob(new int[]{1,2,3,4}, toPrimitives(shape));
66+
dtype = DType.valueOf(call.argument("dtype").toString().toUpperCase());
67+
68+
ArrayList<Integer> shapeList = call.argument("shape");
69+
shape = shapeList.toArray(new Integer[shapeList.size()]);
70+
71+
ArrayList<Double> dataList = call.argument("data");
72+
data = dataList.toArray(new Double[dataList.size()]);
6173

6274
}catch(Exception e){
63-
Log.e("TorchMobile", "", e);
75+
Log.e("TorchMobile", "error parsing arguments", e);
76+
}
77+
78+
//prepare input tensor
79+
final Tensor inputTensor = getInputTensor(dtype, data, shape);
80+
81+
//run model
82+
Tensor outputTensor = null;
83+
try {
84+
outputTensor = module.forward(IValue.from(inputTensor)).toTensor();
85+
}catch(RuntimeException e){
86+
Log.e("TorchMobile", "Your input type " + dtype.toString().toLowerCase() + " (" + Convert.dtypeAsPrimitive(dtype.toString()) +") " + "does not match with model input type",e);
87+
result.success(null);
88+
}
89+
90+
successResult(result, dtype, outputTensor);
91+
92+
break;
93+
case "predictImage":
94+
Module imageModule = null;
95+
Bitmap bitmap = null;
96+
try {
97+
int index = call.argument("index");
98+
byte[] imageData = call.argument("image");
99+
int width = call.argument("width");
100+
int height = call.argument("height");
101+
102+
imageModule = modules.get(index);
103+
104+
bitmap = BitmapFactory.decodeByteArray(imageData,0,imageData.length);
105+
106+
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
107+
108+
}catch (Exception e){
109+
Log.e("TorchMobile", "error reading image", e);
110+
}
111+
112+
final Tensor imageInputTensor = TensorImageUtils.bitmapToFloat32Tensor(bitmap,
113+
TensorImageUtils.TORCHVISION_NORM_MEAN_RGB, TensorImageUtils.TORCHVISION_NORM_STD_RGB);
114+
115+
final Tensor imageOutputTensor = imageModule.forward(IValue.from(imageInputTensor)).toTensor();
116+
117+
float[] scores = imageOutputTensor.getDataAsFloatArray();
118+
119+
ArrayList<Float> out = new ArrayList<>();
120+
for(float f : scores){
121+
out.add(f);
64122
}
123+
124+
result.success(out);
125+
65126
break;
66127
default:
67128
result.notImplemented();
68129
break;
69130
}
70131
}
71132

72-
public static long[] toPrimitives(Long[] objects){
73-
long[] primitives = new long[objects.length];
74-
for(int i = 0; i < objects.length; i++){
75-
primitives[i] = objects[i];
133+
//returns input tensor depending on dtype
134+
private Tensor getInputTensor(DType dtype, Double[] data, Integer[] shape){
135+
switch (dtype){
136+
case FLOAT32:
137+
return Tensor.fromBlob(Convert.toFloatPrimitives(data), Convert.toPrimitives(shape));
138+
case FLOAT64:
139+
return Tensor.fromBlob(Convert.toPrimitives(shape), Convert.toDoublePrimitives(data));
140+
case INT32:
141+
return Tensor.fromBlob(Convert.toIntegerPrimitives(data), Convert.toPrimitives(shape));
142+
case INT64:
143+
return Tensor.fromBlob(Convert.toLongPrimitives(data), Convert.toPrimitives(shape));
144+
case INT8:
145+
return Tensor.fromBlob(Convert.toBytePrimitives(data), Convert.toPrimitives(shape));
146+
case UINT8:
147+
return Tensor.fromBlobUnsigned(Convert.toBytePrimitives(data), Convert.toPrimitives(shape));
148+
default:
149+
return null;
150+
}
151+
}
152+
153+
//gets tensor depending on dtype and creates list of it, which is being returned
154+
private void successResult(Result result, DType dtype, Tensor outputTensor){
155+
switch (dtype){
156+
case FLOAT32:
157+
ArrayList<Float> outputListFloat = new ArrayList<>();
158+
for(float f : outputTensor.getDataAsFloatArray()){
159+
outputListFloat.add(f);
160+
}
161+
result.success(outputListFloat);
162+
break;
163+
case FLOAT64:
164+
ArrayList<Double> outputListDouble = new ArrayList<>();
165+
for(double d : outputTensor.getDataAsDoubleArray()){
166+
outputListDouble.add(d);
167+
}
168+
result.success(outputListDouble);
169+
break;
170+
case INT32:
171+
ArrayList<Integer> outputListInteger = new ArrayList<>();
172+
for(int i : outputTensor.getDataAsIntArray()){
173+
outputListInteger.add(i);
174+
}
175+
result.success(outputListInteger);
176+
break;
177+
case INT64:
178+
ArrayList<Long> outputListLong = new ArrayList<>();
179+
for(long l : outputTensor.getDataAsLongArray()){
180+
outputListLong.add(l);
181+
}
182+
result.success(outputListLong);
183+
break;
184+
case INT8:
185+
ArrayList<Byte> outputListByte = new ArrayList<>();
186+
for(byte b : outputTensor.getDataAsByteArray()){
187+
outputListByte.add(b);
188+
}
189+
result.success(outputListByte);
190+
break;
191+
case UINT8:
192+
ArrayList<Byte> outputListUByte = new ArrayList<>();
193+
for(byte ub : outputTensor.getDataAsUnsignedByteArray()){
194+
outputListUByte.add(ub);
195+
}
196+
result.success(outputListUByte);
197+
break;
198+
default:
199+
result.success(null);
200+
break;
76201
}
77-
return primitives;
78202
}
79203

80204
@Override

example/assets/labels/labels.csv

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
trade,test,ride,leg,excitement,paper,boy,reach,lot,gulf,middle,row,white,citizen,stuck,product,mostly,toward,do,once,now,shown,leader,basic,person,zoo,under,easier,early,eat,girl,influence,camp,everybody,brief,herself,exercise,dark,ball,spend,come,anyway,pupil,great,winter,have,symbol,previous,mark,mysterious,wonder,law,available,sale,operation,stared,are,supper,trap,fallen,fighting,possible,most,picture,automobile,escape,sit,adjective,push,sound,pale,hay,pull,help,cent,discussion,break,taste,till,differ,period,felt,dirt,recently,own,quite,planned,clear,screen,upper,those,hope,definition,twelve,whatever,over,silence,rubber,mirror,goose,shelter,garage,throughout,husband,past,character,dress,forest,forget,disappear,happy,blanket,flat,design,whether,foot,noted,completely,track,using,hole,taught,go,chest,especially,slide,appearance,high,rod,newspaper,strength,everyone,please,careful,recent,magic,church,replace,they,late,rear,harbor,became,hill,unless,extra,driving,grass,finish,jump,gate,its,favorite,anyone,practical,provide,on,eleven,article,choose,safe,straight,stomach,shot,edge,warm,darkness,feel,composed,cave,bit,research,instance,breath,sat,leaf,dog,field,other,view,wonderful,prove,nation,horn,table,fight,farmer,cabin,trail,avoid,stay,lips,hat,vote,equipment,bite,curve,electricity,pound,easily,pot,happily,repeat,rather,production,cause,brain,finger,orange,stick,wise,wagon,lucky,by,bell,vegetable,freedom,library,number,correct,secret,exclaimed,explain,broad,among,won,seeing,men,easy,sail,satellites,came,safety,master,huge,kept,particularly,roll,heard,touch,value,blow,proper,wrong,pleasant,reason,this,date,prepare,garden,sky,cup,setting,contain,valuable,shells,took,stream,beneath,clean,pipe,store,write,primitive,team,wife,onto,work,acres,straw,science,short,later,feed,me,remove,point,practice,hurried,place,youth,yourself,mind,square,according,flight,pool,grade,held,cake,post,become,satisfied,layers,poem,remember,ants,ourselves,cook,sunlight,buffalo,answer,thrown,model,ring,perhaps,mad,central,every,slabs,lying,art,buried,tried,statement,essential,phrase,arrange,browserling,worry,river,syllable,studying,wealth,never,studied,market,chicken,that,nobody,limited,experiment,anything,fact,double,porch,fat,ice,highest,walk,original,silver,bottom,fireplace,here,oil,organization,duty,everywhere,manner,loose,since,drop,shade,future,combination,certain,home,may,fog,special,electric,slow,numeral,leaving,check,strike,thus,stand,putting,official,slowly,mean,factory,water,fort,mission,changing,low,enter,for,conversation,think,saddle,dead,nothing,nuts,volume,across,wild,muscle,simply,letter,sheep,hunt,swung,identity,leave,problem,clothing,create,did,thirty,deep,then,slipped,medicine,behavior,south,lovely,meal,without,any,information,author,larger,mine,guide,lay,coast,sand,brought,universe,record,popular,them,themselves,rough,small,seen,my,all,time,word,count,hair,speed,himself,book,brick,sun,fellow,occasionally,copper,finest,knowledge,twenty,necessary,useful,forward,front,shut,scared,blind,together,remain,courage,greatest,failed,ancient,examine,pleasure,frame,thank,frequently,vast,region,frozen,neck,climb,die,danger,tribe,famous,speak,well,port,sea,snake,birth,blue,red,carbon,plastic,draw,to,salmon,flow,us,quickly,however,coach,catch,boat,either,plate,fur,dream,ocean,herd,graph,amount,west,near,imagine,bet,involved,wheel,yes,vessels,round,mountain,introduced,somewhere,mighty,sudden,joined,football,until,half,image,typical,whom,fewer,back,desert,unknown,sport,drew,certainly,swimming,food,caught,swim,cowboy,paragraph,several,waste,title,consider,eight,four,say,line,meant,event,movie,alphabet,chance,rate,already,discover,string,willing,third,trip,station,smallest,task,instead,tune,bicycle,quick,cattle,except,pour,fall,allow,alike,audience,plant,instrument,care,various,ate,sing,transportation,fix,just,origin,wire,prevent,pass,part,east,death,biggest,fell,journey,grabbed,as,north,chapter,facing,luck,gift,explanation,damage,spread,mile,health,shadow,face,his,concerned,put,sell,loss,dot,brush,whistle,down,bean,sharp,bring,fire,highway,birthday,somehow,jungle,when,dozen,hang,anywhere,construction,fought,raise,complete,knew,effect,pack,list,free,label,police,development,teacher,struck,serve,fence,parent,bar,air,full,pattern,lose,cream,surface,bat,donkey,throw,sold,bare,hollow,how,signal,ship,arrive,were,tropical,eaten,wish,tube,iron,must,parts,angle,fed,noise,direction,had,fear,younger,board,pressure,smile,higher,more,aboard,guess,none,busy,yellow,cut,process,silk,stopped,mathematics,heat,itself,nails,monkey,bark,tie,milk,voyage,southern,settle,beautiful,we,chain,neighborhood,laid,pie,adult,clearly,inside,indicate,needle,also,education,atmosphere,change,chief,badly,include,rocky,regular,scientist,carefully,merely,exact,tool,hurry,driver,strong,tonight,shoulder,search,threw,national,consonant,basis,state,scene,buy,widely,series,slept,collect,married,offer,happened,way,dug,moving,balloon,sleep,excited,suit,sitting,faster,getting,pay,fierce,success,car,handsome,sense,paint,city,road,pet,another,calm,spring,stepped,carry,wrapped,instant,ahead,structure,large,rise,airplane,naturally,want,constantly,tank,successful,although,broken,trace,machinery,hard,lungs,box,season,mainly,fairly,him,vertical,done,suddenly,whose,train
2+
warn,thumb,almost,young,smell,doctor,year,bill,show,what,born,how,chosen,volume,solve,good,protection,characteristic,clothing,search,dry,told,fruit,blue,carbon,government,throw,fish,slip,common,those,information,enjoy,fog,sad,only,know,worse,wild,chart,empty,indeed,swimming,master,edge,it,across,spell,explore,immediately,program,bare,product,then,all,forth,leaving,although,orange,nuts,build,something,key,bee,able,fight,position,below,fat,ice,deeply,mixture,welcome,frighten,my,sale,flies,oxygen,enemy,value,street,blind,freedom,remain,speech,it,writer,gravity,skin,unusual,shut,service,beside,school,pale,running,discover,personal,donkey,possible,just,bridge,aloud,till,clear,vegetable,phrase,win,now,appropriate,lost,log,foot,invented,whether,consider,his,came,there,coast,must,fair,again,summer,out,first,work,broke,gain,community,beneath,correctly,shells,directly,smallest,dawn,variety,cheese,vote,belt,bush,law,five,colony,forward,rear,remarkable,root,pie,older,higher,compound,log,while,society,gun,reason,pipe,post,road,this,trick,cabin,gate,closer,scared,your,board,list,classroom,dull,minute,pipe,sand,chamber,nearby,nation,mass,nearby,battle,chose,does,smaller,lady,shelf,bowl,know,through,slabs,wooden,topic,add,amount,hurry,car,low,lying,dollar,saved,heat,curve,our,rule,mad,unknown,push,fuel,dance,evening,angle,hard,hundred,standard,flight,thou,aid,show,headed,wool,cent,attack,over,shade,door,especially,hung,themselves,cookies,grade,lower,capital,strike,contrast,draw,stand,grabbed,sight,balance,tune,ice,volume,exciting,pride,appearance,support,triangle,certainly,slabs,burst,up,certainly,drew,wire,hang,thirty,cloud,truck,golden,seat,moving,bat,voice,bone,leader,society,get,pleasure,soon,chief,blew,deal,feel,flame,meal,fireplace,facing,being,hurried,prepare,drew,enough,former,youth,wrong,contain,hardly,go,straw,full,essential,soil,century,way,such,out,nearly,principal,forest,pressure,then,grade,date,atom,park,noted,old,tobacco,organization,cannot,want,subject,flow,onto,active,allow,plate,represent,dropped,cream,directly,immediately,spider,afternoon,older,each,relationship,twice,put,drawn,anybody,jungle,sleep,halfway,produce,continued,temperature,still,he,change,motor,giant,community,wrote,wonder,attack,event,still,went,wife,art,us,root,into,short,against,additional,tomorrow,master,pen,influence,settle,key,remain,own,sky,post,massage,proper,clay,price,dish,hunter,nice,division,enter,parallel,terrible,talk,pound,lovely,open,create,notice,went,whatever,company,judge,doll,browserling,control,huge,fewer,wide,piano,opportunity,corn,prevent,actually,due,moment,fireplace,now,thumb,breathe,alphabet,shorter,person,driven,worry,surprise,basic,ball,shore,pond,last,claws,nearby,throughout,gentle,inside,house,break,deal,instant,blood,television,rabbit,continent,meat,everybody,sort,write,lose,claws,very,citizen,right,sheep,activity,nest,whatever,silence,both,sort,improve,station,unknown,variety,wave,trap,believed,exercise,death,knew,shorter,fully,worry,blew,specific,slabs,closer,official,came,chart,pound,getting,born,general,neighbor,know,such,board,hungry,poetry,chamber,told,merely,headed,that,sad,twice,nature,manner,monkey,spring,production,finest,raw,combination,weather,did,herself,kids,evidence,situation,eleven,use,replied,cheese,land,scale,store,ten,position,threw,twice,height,drove,function,excitement,dirty,harbor,announced,salmon,engineer,save,cook,verb,excitement,flies,look,whole,important,percent,forgotten,care,tried,doubt,straw,deal,longer,break,gain,window,magic,lot,shallow,organization,rising,lake,leather,adventure,weak,so,buy,listen,stick,create,pole,stage,dozen,underline,make,putting,aside,weigh,browserling,river,toy,gravity,run,stick,coach,newspaper,willing,pool,market,kill,angry,brain,hope,whose,daughter,everything,accident,race,husband,captured,cause,stiff,notice,flame,flag,straw,stiff,into,where,made,single,theory,flew,title,block,burst,meant,simply,clear,event,mathematics,two,drive,careful,relationship,bean,except,my,blow,charge,wind,finally,local,sale,distance,living,tonight,deep,have,situation,greater,statement,either,flower,wool,lose,meat,beginning,diagram,generally,front,gray,page,begun,your,helpful,cost,slight,sleep,behavior,powerful,row,brave,beside,bring,blood,belong,excitement,conversation,main,work,break,captain,highest,know,act,noun,triangle,return,setting,cast,goose,around,list,feathers,bridge,contrast,mail,colony,drawn,stay,machinery,picture,regular,community,driver,poem,cup,explore,stopped,meant,company,say,free,split,trip,be,gain,base,gasoline,pink,season,ship,fellow,monkey,wire,brush,ordinary,upper,inch,us,effect,aboard,alphabet,exactly,had,strip,goes,stage,milk,fastened,most,pool,nearest,four,stood,wooden,read,pony,field,wealth,movie,stone,luck,fifty,action,spirit,careful,scientist,blanket,food,tomorrow,stems,thousand,per,wrote,sheep,across,invented,suggest,book,away,wonderful,hardly,shadow,rapidly,finger,double,everyone,huge,particularly,promised,near,memory,military,sold,mix,rough,lady,muscle,contain,myself,couple,indicate,long,spirit,discover,myself,never,continent,picture,shot,basic,declared,time,honor,generally,fallen,shall,struggle,soldier,loud,cheese,string,wolf,for,hang,entirely,notice,can,fifth,easier,trip,sick,declared,college,follow,office

example/assets/models/custom_model.pt

3.27 KB
Binary file not shown.
File renamed without changes.

0 commit comments

Comments
 (0)