forked from joshuamyers-dev/react-native-coreml
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
executable file
·75 lines (72 loc) · 2.11 KB
/
index.ts
File metadata and controls
executable file
·75 lines (72 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { NativeModules, Image, Platform } from "react-native";
const { resolveAssetSource } = Image;
class RNCoreMLClass {
compileModel: (sourcepath: string) => Promise<string>;
classifyImageWithModel: (imagepath: string, modelpath: string) => Promise<Array<Object>>;
predictFromDataWithModel: (data: object, modelpath: string) => Promise<object>;
saveMultiArray: (key: string, savePath: string) => Promise<string>;
mainBundleURL: string;
mainBundlePath: string;
}
const RNCoreML: RNCoreMLClass = NativeModules.RNCoreML;
const { mainBundlePath, mainBundleURL } = RNCoreML;
const fixURL = sourcepath => {
if (typeof sourcepath === "string") {
if (sourcepath.includes("/")) return sourcepath;
else return mainBundleURL + "/" + sourcepath;
}
if (sourcepath.uri) {
return sourcepath.uri;
}
const { uri } = resolveAssetSource(sourcepath);
return uri;
};
const compileModel = async sourcepath => {
return await RNCoreML.compileModel(fixURL(sourcepath));
};
const classifyImage = async (imagePath, modelPath) => {
return await RNCoreML.classifyImageWithModel(fixURL(imagePath), fixURL(modelPath));
};
const getTopResult = arr => {
return arr[0];
};
const getTopFiveResults = arr => {
return arr.slice(0, 4);
};
const classifyTopFive = async (imagePath, modelPath) => {
const arr = classifyImage(imagePath, modelPath);
return getTopFiveResults(arr);
};
const classifyTopValue = async (imagePath, modelPath) => {
const arr = classifyImage(imagePath, modelPath);
return getTopResult(arr);
};
const predict = async (dictionary, modelPath) => {
const obj = await RNCoreML.predictFromDataWithModel(dictionary, fixURL(modelPath));
return obj;
};
const saveMultiArray = async (key, savePath) => {
if (!savePath) savePath = null;
const newPath = await RNCoreML.saveMultiArray(key, savePath);
return newPath;
};
export default {
compileModel,
classifyImage,
classifyTopFive,
classifyTopValue,
predict,
saveMultiArray,
mainBundlePath,
mainBundleURL
};
export {
compileModel,
classifyImage,
classifyTopFive,
classifyTopValue,
predict,
saveMultiArray,
mainBundlePath,
mainBundleURL
};