summaryrefslogtreecommitdiffstats
path: root/core/java/android/gesture/LetterRecognizer.java
blob: 9e801ed4356295d7ff2d0bec3b0883f58a6756a3 (plain)
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.gesture;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import static android.gesture.GestureConstants.LOG_TAG;

public class LetterRecognizer {
    public final static int RECOGNIZER_LATIN_LOWERCASE = 0;
    static final String GESTURE_FILE_NAME = "letters.gestures";

    private final static int ADJUST_RANGE = 3;    

    private SigmoidUnit[] mHiddenLayer;
    private SigmoidUnit[] mOutputLayer;

    private final String[] mClasses;

    private final int mPatchSize;
    
    private GestureLibrary mGestureLibrary;

    private final Comparator<Prediction> mComparator = new PredictionComparator();

    private static class SigmoidUnit {
        final float[] mWeights;

        SigmoidUnit(float[] weights) {
            mWeights = weights;
        }

        private float compute(float[] inputs) {
            float sum = 0;

            final int count = inputs.length;
            final float[] weights = mWeights;

            for (int i = 0; i < count; i++) {
                sum += inputs[i] * weights[i];
            }
            sum += weights[weights.length - 1];

            return 1.0f / (float) (1 + Math.exp(-sum));
        }
    }

    public static LetterRecognizer getLetterRecognizer(Context context, int type) {
        switch (type) {
            case RECOGNIZER_LATIN_LOWERCASE: {
                return createFromResource(context, com.android.internal.R.raw.latin_lowercase);
            }
        }
        return null;
    }

    private LetterRecognizer(int numOfInput, int numOfHidden, String[] classes) {
        mPatchSize = (int) Math.sqrt(numOfInput);
        mHiddenLayer = new SigmoidUnit[numOfHidden];
        mClasses = classes;
        mOutputLayer = new SigmoidUnit[classes.length];
    }

    public ArrayList<Prediction> recognize(Gesture gesture) {
        return recognize(gesture, null);
    }

    public ArrayList<Prediction> recognize(Gesture gesture, ArrayList<Prediction> predictions) {
        float[] query = GestureUtilities.spatialSampling(gesture, mPatchSize);
        predictions = classify(query, predictions);
        adjustPrediction(gesture, predictions);
        return predictions;
    }

    private ArrayList<Prediction> classify(float[] vector, ArrayList<Prediction> predictions) {
        if (predictions == null) {
            predictions = new ArrayList<Prediction>();
        } else {
            predictions.clear();
        }

        final float[] intermediateOutput = compute(mHiddenLayer, vector);
        final float[] output = compute(mOutputLayer, intermediateOutput);

        double sum = 0;

        final String[] classes = mClasses;
        final int count = classes.length;

        for (int i = 0; i < count; i++) {
            double score = output[i];
            sum += score;
            predictions.add(new Prediction(classes[i], score));
        }

        for (int i = 0; i < count; i++) {
            predictions.get(i).score /= sum;
        }

        Collections.sort(predictions, mComparator);

        return predictions;
    }

    private float[] compute(SigmoidUnit[] layer, float[] input) {
        final float[] output = new float[layer.length];
        final int count = layer.length;

        for (int i = 0; i < count; i++) {
            output[i] = layer[i].compute(input);
        }

        return output;
    }

    private static LetterRecognizer createFromResource(Context context, int resourceID) {
        final Resources resources = context.getResources();

        DataInputStream in = null;
        LetterRecognizer classifier = null;

        try {
            in = new DataInputStream(new BufferedInputStream(resources.openRawResource(resourceID),
                    GestureConstants.IO_BUFFER_SIZE));

            final int version = in.readShort();

            switch (version) {
                case 1:
                    classifier = readV1(in);
                    break;
                default:
                    Log.d(LOG_TAG, "Couldn't load handwriting data: version " + version +
                            " not supported");
                    break;
            }

        } catch (IOException e) {
            Log.d(LOG_TAG, "Failed to load handwriting data:", e);
        } finally {
            GestureUtilities.closeStream(in);
        }

        return classifier;
    }

    private static LetterRecognizer readV1(DataInputStream in) throws IOException {

        final int iCount = in.readInt();
        final int hCount = in.readInt();
        final int oCount = in.readInt();

        final String[] classes = new String[oCount];
        for (int i = 0; i < classes.length; i++) {
            classes[i] = in.readUTF();
        }

        final LetterRecognizer classifier = new LetterRecognizer(iCount, hCount, classes);
        final SigmoidUnit[] hiddenLayer = new SigmoidUnit[hCount];
        final SigmoidUnit[] outputLayer = new SigmoidUnit[oCount];

        for (int i = 0; i < hCount; i++) {
            final float[] weights = new float[iCount + 1];
            for (int j = 0; j <= iCount; j++) {
                weights[j] = in.readFloat();
            }
            hiddenLayer[i] = new SigmoidUnit(weights);
        }

        for (int i = 0; i < oCount; i++) {
            final float[] weights = new float[hCount + 1];
            for (int j = 0; j <= hCount; j++) {
                weights[j] = in.readFloat();
            }
            outputLayer[i] = new SigmoidUnit(weights);
        }

        classifier.mHiddenLayer = hiddenLayer;
        classifier.mOutputLayer = outputLayer;

        return classifier;
    }

    /**
     * TODO: Publish this API once we figure out where we should save the personzlied
     * gestures, and how to do so across all apps
     *
     * @hide
     */
    public boolean save() {
        if (mGestureLibrary != null) {
            return mGestureLibrary.save();
        }
        return false;
    }

    /**
     * TODO: Publish this API once we figure out where we should save the personzlied
     * gestures, and how to do so across all apps
     *
     * @hide
     */
    public void setPersonalizationEnabled(boolean enabled) {
        if (enabled) {
            mGestureLibrary = new GestureLibrary(GESTURE_FILE_NAME);
            mGestureLibrary.setSequenceType(GestureLibrary.SEQUENCE_INVARIANT);
            mGestureLibrary.load();
        } else {
            mGestureLibrary = null;
        }
    }

    /**
     * TODO: Publish this API once we figure out where we should save the personzlied
     * gestures, and how to do so across all apps
     *
     * @hide
     */
    public void addExample(String letter, Gesture example) {
        if (mGestureLibrary != null) {
            mGestureLibrary.addGesture(letter, example);
        }
    }
    
    private void adjustPrediction(Gesture query, ArrayList<Prediction> predictions) {
        if (mGestureLibrary != null) {
            final ArrayList<Prediction> results = mGestureLibrary.recognize(query);
            final HashMap<String, Prediction> topNList = new HashMap<String, Prediction>();

            for (int j = 0; j < ADJUST_RANGE; j++) {
                Prediction prediction = predictions.remove(0);
                topNList.put(prediction.name, prediction);
            }

            final int count = results.size();
            for (int j = count - 1; j >= 0 && !topNList.isEmpty(); j--) {
                final Prediction item = results.get(j);
                final Prediction original = topNList.get(item.name);
                if (original != null) {
                    predictions.add(0, original);
                    topNList.remove(item.name);
                }
            }
        }
    }

    private static class PredictionComparator implements Comparator<Prediction> {
        public int compare(Prediction object1, Prediction object2) {
            double score1 = object1.score;
            double score2 = object2.score;
            if (score1 > score2) {
                return -1;
            } else if (score1 < score2) {
                return 1;
            } else {
                return 0;
            }
        }
    }
}