-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathModelUtils.ts
More file actions
212 lines (183 loc) · 7.46 KB
/
ModelUtils.ts
File metadata and controls
212 lines (183 loc) · 7.46 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import tmPose from '@teachablemachine/pose';
import tmImage from '@teachablemachine/image';
import * as speechCommands from '@tensorflow-models/speech-commands';
export default class TeachableMachine {
latestAudioResults: any;
predictionState;
modelConfidences = {};
maxConfidence: number = null;
teachableImageModel;
isPredicting: number = 0;
ModelType = {
POSE: 'pose',
IMAGE: 'image',
AUDIO: 'audio',
};
constructor() {
this.predictionState = {};
}
useModel = async (url: string): Promise<{type: "success" | "error" | "warning", msg: string}> => {
try {
const modelUrl = this.modelArgumentToURL(url);
console.log('Loading model from URL:', modelUrl);
// Initialize prediction state if needed
this.predictionState[modelUrl] = {};
// Load and initialize the model
const { model, type } = await this.initModel(modelUrl);
this.predictionState[modelUrl].modelType = type;
this.predictionState[modelUrl].model = model;
// Update the current model reference
this.teachableImageModel = modelUrl;
return {
type: "success",
msg: "Model loaded successfully"
};
} catch (e) {
console.error('Error loading model:', e);
this.teachableImageModel = null;
return {
type: "error",
msg: "Failed to load model"
};
}
}
modelArgumentToURL = (modelArg: string) => {
// Convert user-provided model URL/ID to the correct format
const endpointProvidedFromInterface = "https://teachablemachine.withgoogle.com/models/";
const redirectEndpoint = "https://storage.googleapis.com/tm-model/";
return modelArg.startsWith(endpointProvidedFromInterface)
? modelArg.replace(endpointProvidedFromInterface, redirectEndpoint)
: redirectEndpoint + modelArg + "/";
}
initModel = async (modelUrl: string) => {
const avoidCache = `?x=${Date.now()}`;
const modelURL = modelUrl + "model.json" + avoidCache;
const metadataURL = modelUrl + "metadata.json" + avoidCache;
// First try loading as an image model
try {
const customMobileNet = await tmImage.load(modelURL, metadataURL);
// Check if it's actually an audio model
if ((customMobileNet as any)._metadata.hasOwnProperty('tfjsSpeechCommandsVersion')) {
const recognizer = await speechCommands.create("BROWSER_FFT", undefined, modelURL, metadataURL);
await recognizer.ensureModelLoaded();
// Setup audio listening
await recognizer.listen(async result => {
this.latestAudioResults = result;
}, {
includeSpectrogram: true,
probabilityThreshold: 0.75,
invokeCallbackOnNoiseAndUnknown: true,
overlapFactor: 0.50
});
return { model: recognizer, type: this.ModelType.AUDIO };
}
// Check if it's a pose model
else if ((customMobileNet as any)._metadata.packageName === "@teachablemachine/pose") {
const customPoseNet = await tmPose.load(modelURL, metadataURL);
return { model: customPoseNet, type: this.ModelType.POSE };
}
// Otherwise it's an image model
else {
return { model: customMobileNet, type: this.ModelType.IMAGE };
}
} catch (e) {
console.error("Failed to load model:", e);
throw e;
}
}
getPredictionFromModel = async (modelUrl: string, frame: ImageBitmap) => {
const { model, modelType } = this.predictionState[modelUrl];
switch (modelType) {
case this.ModelType.IMAGE:
if (!frame) return null;
return await model.predict(frame);
case this.ModelType.POSE:
if (!frame) return null;
const { pose, posenetOutput } = await model.estimatePose(frame);
return await model.predict(posenetOutput);
case this.ModelType.AUDIO:
if (this.latestAudioResults) {
return model.wordLabels().map((label, i) => ({
className: label,
probability: this.latestAudioResults.scores[i]
}));
}
return null;
}
}
private getPredictionStateOrStartPredicting(modelUrl: string) {
if (!modelUrl || !this.predictionState || !this.predictionState[modelUrl]) {
console.warn('No prediction state available for model:', modelUrl);
return null;
}
return this.predictionState[modelUrl];
}
model_match(state) {
const modelUrl = this.teachableImageModel;
const className = state;
const predictionState = this.getPredictionStateOrStartPredicting(modelUrl);
if (!predictionState) {
return false;
}
const currentMaxClass = predictionState.topClass;
return (currentMaxClass === String(className));
}
getModelClasses(): string[] {
if (
!this.teachableImageModel ||
!this.predictionState ||
!this.predictionState[this.teachableImageModel] ||
!this.predictionState[this.teachableImageModel].hasOwnProperty('model')
) {
return ["Select a class"];
}
if (this.predictionState[this.teachableImageModel].modelType === this.ModelType.AUDIO) {
return this.predictionState[this.teachableImageModel].model.wordLabels();
}
return this.predictionState[this.teachableImageModel].model.getClassLabels();
}
getModelPrediction() {
const modelUrl = this.teachableImageModel;
const predictionState: { topClass: string } = this.getPredictionStateOrStartPredicting(modelUrl);
if (!predictionState) {
console.error("No prediction state found");
return '';
}
return predictionState.topClass;
}
async predictAllBlocks(frame: ImageBitmap) {
for (let modelUrl in this.predictionState) {
if (!this.predictionState[modelUrl].model) {
console.log('No model found for:', modelUrl);
continue;
}
if (this.teachableImageModel !== modelUrl) {
console.log('Model URL mismatch:', modelUrl);
continue;
}
++this.isPredicting;
const prediction = await this.predictModel(modelUrl, frame);
this.predictionState[modelUrl].topClass = prediction;
--this.isPredicting;
}
}
private async predictModel(modelUrl: string, frame: ImageBitmap) {
const predictions = await this.getPredictionFromModel(modelUrl, frame);
if (!predictions) {
return;
}
let maxProbability = 0;
let maxClassName = "";
for (let i = 0; i < predictions.length; i++) {
const probability = predictions[i].probability.toFixed(2);
const className = predictions[i].className;
this.modelConfidences[className] = probability;
if (probability > maxProbability) {
maxClassName = className;
maxProbability = probability;
}
}
this.maxConfidence = maxProbability;
return maxClassName;
}
}