-
Notifications
You must be signed in to change notification settings - Fork 169
/
wit-example-viewer.ts
2132 lines (1961 loc) · 70.1 KB
/
wit-example-viewer.ts
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
import BytesList from 'goog:proto.tensorflow.BytesList';
import Example from 'goog:proto.tensorflow.Example';
import Feature from 'goog:proto.tensorflow.Feature';
import FeatureList from 'goog:proto.tensorflow.FeatureList';
import FeatureLists from 'goog:proto.tensorflow.FeatureLists';
import Features from 'goog:proto.tensorflow.Features';
import FloatList from 'goog:proto.tensorflow.FloatList';
import Int64List from 'goog:proto.tensorflow.Int64List';
import SequenceExample from 'goog:proto.tensorflow.SequenceExample';
namespace wit_example_viewer {
// SaliencyMap is a map of feature names to saliency values for their feature
// values. The saliency can be a single number for all values in a feature value
// list, or a number per value. For sequence examples, there is saliency
// information for each sequence number in the example.
// TODO(jwexler): Strengthen the difference between array of SaliencyValues and
// arrays of numbers in a SaliencyValue.
export type SaliencyValue = number | number[];
export type SaliencyMap = {
[feature: string]: SaliencyValue | SaliencyValue[];
};
// A helper interface that tracks a feature's values and its name.
export interface NameAndFeature {
name: string;
feature: Feature | FeatureList;
}
export type OnloadFunction = (feat: string, image: HTMLImageElement) => void;
// Information about a single image feature.
interface ImageInformation {
// image onload function, for re-calling when saliency setting changes.
onload?: OnloadFunction;
// Raw ImageData arrays for the image. One for the original image, one for the
// grayscale image, to be overlaid with a saliency mask.
imageData?: Uint8ClampedArray;
imageGrayscaleData?: Uint8ClampedArray;
// The image element that initially loads the image data for the feature.
imageElement?: HTMLImageElement;
// Currently applied transform to the image.
transform?: d3.ZoomTransform;
}
// Information stored in data attributes of controls in the visualization.
interface DataFromControl {
// The feature being altered by this control.
feature: string;
// The index of the value in the value list being altered by this control.
valueIndex: number;
// The sequence number of the value list being altered by this control.
seqNum: number;
}
// HTMLElement with bound data attributes to track feature value information.
interface HTMLElementWithData extends HTMLElement {
dataFeature: string;
dataIndex: number;
dataSeqNum: number;
}
export interface HTMLDialogElement extends HTMLElement {
open: () => void;
}
const INT_FEATURE_NAME = 'int';
const FLOAT_FEATURE_NAME = 'float';
const BASE_64_IMAGE_ENCODING_PREFIX = 'base64,';
const CHANGE_CALLBACK_TIMER_DELAY_MS = 1000;
const noAttributionColor = '#fff';
const defaultTextColor = '#3c4043';
// Regex to find bytes features that are encoded images. Follows the guide at
// go/tf-example.
const IMG_FEATURE_REGEX = /^image\/([^\/]+\/)*encoded$/;
// Corresponds to a length of a Uint8Array of size 250MB. Above this size we
// will not decode a bytes list into a string.
const MAX_BYTES_LIST_LENGTH = (1024 * 1024 * 250) / 8;
// The max ratio to blend saliency map colors with a grayscaled version of an
// image feature, to create a visually-useful saliency mask on an image.
const IMG_SALIENCY_MAX_COLOR_RATIO = 0.5;
// String returned when a decoded string feature is too large to display.
const MAX_STRING_INDICATION = 'String too large to display';
// D3 zoom extent range for image zooming.
const ZOOM_EXTENT: [number, number] = [1, 20];
const DEFAULT_WINDOW_WIDTH = 256;
const DEFAULT_WINDOW_CENTER = 128;
Polymer({
is: 'wit-example-viewer',
properties: {
example: {type: Object},
serializedExample: {type: String, observer: 'updateExample'},
serializedSeqExample: {type: String, observer: 'updateSeqExample'},
json: {type: Object, observer: 'createExamplesFromJson'},
saliency: {type: Object, value: {}},
saliencyJsonString: {type: String, observer: 'haveSaliencyJson'},
readonly: {type: Boolean, value: false},
seqNumber: {type: Number, value: 0, observer: 'newSeqNum'},
isSequence: Boolean,
changeCallbackTimer: Number,
ignoreChange: Boolean,
minSal: Number,
maxSal: Number,
showSaliency: {type: Boolean, value: true},
imageInfo: {type: Object, value: {}},
windowWidth: {type: Number, value: DEFAULT_WINDOW_WIDTH},
windowCenter: {type: Number, value: DEFAULT_WINDOW_CENTER},
saliencyCutoff: {type: Number, value: 0},
hasImage: {type: Boolean, value: true},
allowImageControls: {type: Boolean, value: false},
imageScalePercentage: {type: Number, value: 100},
features: {type: Object, computed: 'getFeatures(example)'},
featuresList: {
type: Object,
computed: 'getFeaturesList(features, compareFeatures)',
},
seqFeatures: {type: Object, computed: 'getSeqFeatures(example)'},
seqFeaturesList: {
type: Object,
computed: 'getFeaturesList(seqFeatures, compareSeqFeatures)',
},
maxSeqNumber: {
type: Number,
computed: 'getMaxSeqNumber(seqFeaturesList)',
},
colors: Object,
highlightDifferences: {
type: Boolean,
value: true,
},
displayMode: {type: String, value: 'grid'},
featureSearchValue: {type: String, value: '', notify: true},
filteredFeaturesList: {type: Object},
filteredSeqFeaturesList: {type: Object},
focusedFeatureName: String,
focusedFeatureValueIndex: Number,
focusedSeqNumber: Number,
showDeleteValueButton: {type: Boolean, value: false},
expandedFeatures: {type: Object, value: {}},
expandAllFeatures: {type: Boolean, value: false},
zeroIndex: {type: Number, value: 0},
compareJson: {type: Object, observer: 'createCompareExamplesFromJson'},
compareExample: {type: Object},
compareFeatures: {
type: Object,
computed: 'getFeatures(compareExample)',
observer: 'updateCompareMode',
},
compareSeqFeatures: {
type: Object,
computed: 'getSeqFeatures(compareExample)',
observer: 'updateCompareMode',
},
// The order to sort features. Can be 'attribution',
// 'reverse-attribution', or 'alphabetical'.
sortOrder: {
type: String,
value: 'attribution',
},
compareMode: Boolean,
compareImageInfo: {type: Object, value: {}},
compareTitle: String,
textColorFunction: Object,
},
observers: [
'displaySaliency(saliency, example)',
'haveSaliency(filteredFeaturesList, saliency, colors, showSaliency, saliencyCutoff)',
'seqSaliency(seqNumber, seqFeaturesList, saliency, colors, showSaliency, saliencyCutoff)',
'setFilteredFeaturesList(featuresList, featureSearchValue, saliency, sortOrder)',
'setFilteredSeqFeaturesList(seqFeaturesList, featureSearchValue, saliency, sortOrder)',
],
isExpanded: function(featName: string, expandAllFeatures: boolean) {
return (
this.expandAllFeatures ||
this.sanitizeFeature(featName) in this.expandedFeatures
);
},
updateExample: function() {
this.deserializeExample(
this.serializedExample,
Example.deserializeBinary
);
},
// tslint:disable-next-line:no-unused-variable called as observer
updateSeqExample: function() {
this.deserializeExample(
this.serializedSeqExample,
SequenceExample.deserializeBinary
);
},
/* Helper method to encode a string into a typed array. */
stringToUint8Array: function(str: string) {
return new (window as any).TextEncoder().encode(str);
},
deserializeExample: function(
serializedProto: string,
deserializer: (arr: Uint8Array) => Example | SequenceExample
) {
// If ignoreChange is set then do not deserialized a newly set serialized
// example, which would cause the entire visualization to re-render.
if (this.ignoreChange) {
return;
}
const bytes = this.decodedStringToCharCodes(atob(serializedProto));
this.example = deserializer(bytes);
},
/** A computed map of all standard features in an example. */
getFeatures: function(example: Example | SequenceExample) {
// Reset our maps of image information when a new example is supplied.
this.imageInfo = {};
this.hasImage = false;
if (example == null) {
return new Map<string, FeatureList>([]);
}
if (example instanceof Example) {
this.isSequence = false;
if (!example.hasFeatures()) {
example.setFeatures(new Features());
}
return example.getFeatures()!.getFeatureMap();
} else {
this.isSequence = true;
if (!example.hasContext()) {
example.setContext(new Features());
}
return example.getContext()!.getFeatureMap();
}
},
/**
* A computed list of all standard features in an example, for driving the
* display.
*/
getFeaturesList: function(features: any, compareFeatures: any) {
if (features == null) {
return [];
}
const featuresList: NameAndFeature[] = [];
const featureSet: {[key: string]: boolean} = {};
let it = features.keys();
if (it) {
let next = it.next();
while (!next.done) {
featuresList.push({
name: next.value,
feature: features.get(next.value)!,
});
featureSet[next.value] = true;
next = it.next();
}
}
if (compareFeatures == null) {
return featuresList;
}
it = compareFeatures.keys();
if (it) {
let next = it.next();
while (!next.done) {
if (next.value in featureSet) {
next = it.next();
continue;
}
featuresList.push({
name: next.value,
feature: compareFeatures.get(next.value)!,
});
featureSet[next.value] = true;
next = it.next();
}
}
return featuresList;
},
/** A computed map of all sequence features in an example. */
getSeqFeatures: function(example: Example | SequenceExample) {
if (example == null || example instanceof Example) {
return new Map<string, FeatureList>([]);
}
return (this.example as SequenceExample)
.getFeatureLists()!
.getFeatureListMap();
},
setFilteredFeaturesList: function(
featureList: NameAndFeature[],
searchValue: string,
saliency: SaliencyMap,
sortOrder: string
) {
this.filteredFeaturesList = [];
this.filteredFeaturesList = this.getFilteredFeaturesList(
featureList,
searchValue,
saliency,
sortOrder
);
},
setFilteredSeqFeaturesList: function(
seqFeatureList: NameAndFeature[],
searchValue: string,
saliency: SaliencyMap,
sortOrder: string
) {
this.filteredSeqFeaturesList = [];
this.filteredSeqFeaturesList = this.getFilteredFeaturesList(
seqFeatureList,
searchValue,
saliency,
sortOrder
);
},
getFilteredFeaturesList: function(
featureList: NameAndFeature[],
searchValue: string,
saliency: SaliencyMap,
sortOrder: string
) {
if (featureList == null) {
return;
}
let filtered = featureList;
const checkSal =
saliency &&
Object.keys(saliency).length > 0 &&
sortOrder != 'alphabetical';
// Create a dict of feature names to the total saliency of all
// its feature values, to sort salient features at the top.
const saliencyTotals = checkSal
? Object.assign(
{},
...Object.keys(saliency).map((name) => ({
[name]:
typeof saliency[name] == 'number'
? (saliency[name] as number)
: (saliency[name] as Array<number>).reduce(
(total, cur) => total + cur,
0
),
}))
)
: {};
if (searchValue != '') {
const re = new RegExp(searchValue, 'i');
filtered = featureList.filter((feature) => re.test(feature.name));
}
const sorted = filtered.sort((a, b) => {
if (this.isImage(a.name) && !this.isImage(b.name)) {
return -1;
} else if (this.isImage(b.name) && !this.isImage(a.name)) {
return 1;
} else {
if (checkSal) {
if (a.name in saliency && !(b.name in saliency)) {
return -1;
} else if (b.name in saliency && !(a.name in saliency)) {
return 1;
} else {
const diff =
sortOrder == 'attribution'
? saliencyTotals[b.name] - saliencyTotals[a.name]
: sortOrder == 'reverse-attribution'
? saliencyTotals[a.name] - saliencyTotals[b.name]
: Math.abs(saliencyTotals[b.name]) -
Math.abs(saliencyTotals[a.name]);
if (diff != 0) {
return diff;
}
}
}
return a.name.localeCompare(b.name);
}
});
return sorted;
},
/**
* Returns the maximum sequence length in the sequence example, or -1 if
* there are no sequences.
*/
getMaxSeqNumber: function() {
let max = -1;
for (const feat of this.seqFeaturesList) {
const list = feat.feature as FeatureList;
if (list && list.getFeatureList().length - 1 > max) {
max = list.getFeatureList().length - 1;
}
}
return max;
},
haveSaliencyJson: function() {
this.saliency = JSON.parse(this.saliencyJsonString);
},
selectAll: function(query: string) {
return d3.selectAll(Polymer.dom(this.root).querySelectorAll(
query
) as any);
},
displaySaliency: function(saliency: SaliencyMap) {
const feats = Object.keys(saliency);
const salJson: any = {};
// Create a tf.Example json containing the saliency for each feature.
for (let i = 0; i < feats.length; i++) {
const feat = feats[i];
let salValues = saliency[feat];
if (!Array.isArray(salValues)) {
salValues = [salValues];
}
salJson[feat] = {
floatList: {
value: (salValues as number[]).map((sal: number) =>
d3.format('.4f')(sal)
),
},
};
}
this.saliencyJson = {features: {feature: salJson}};
// Set the compareJson to this, for display beside the feature values.
this.compareJson = this.saliencyJson;
},
haveSaliency: function() {
// Saliency-coloring waits until the display elements have been updated
// to avoid coloring divs that are then re-ordered/re-used/re-named by
// the dom-repeat of feature divs.
requestAnimationFrame(() => this._haveSaliencyImpl());
},
_haveSaliencyImpl: function() {
// TODO(jameswex): Color counterfactual column if using attribution-based
// counterfactuals.
// Reset all value pills to default settings.
this.selectAll('.value-pill')
.style('background', noAttributionColor)
.attr('title', '')
.style('color', defaultTextColor);
if (
!this.filteredFeaturesList ||
!this.saliency ||
Object.keys(this.saliency).length === 0 ||
!this.colors
) {
return;
}
// Color the text of each input element of each feature according to the
// provided saliency information.
for (const feat of this.filteredFeaturesList) {
const val = this.saliency[feat.name] as SaliencyValue;
// If there is no saliency information for the feature, do not color it.
if (val == null) {
continue;
}
// Set background color, tooltip, and text color, which are all based
// on saliency score.
const colorFn = Array.isArray(val)
? (d: {}, i: number) => this.getColorForSaliency(val[i])
: () => this.getColorForSaliency(val);
this.selectAll(`.${this.sanitizeFeature(feat.name)}.value-pill`)
.style(
'background',
this.showSaliency ? colorFn : () => noAttributionColor
)
.attr(
'title',
(d: {}, i: number) =>
'Attribution: ' +
d3.format('.4f')(Array.isArray(val) ? val[i] : val)
)
.style('color', (d: {}, i: number) => {
const num = Array.isArray(val) ? val[i] : val;
return this.textColorFunction(num, this.minSal, this.maxSal);
});
// Color the "more feature values" button with the most extreme saliency
// of any of the feature values hidden behind the button.
if (Array.isArray(val)) {
const valArray = val as Array<number>;
const moreButton = this.selectAll(
`paper-button.${this.sanitizeFeature(feat.name)}.value-pill`
);
let mostExtremeSal = 0;
for (let i = 1; i < valArray.length; i++) {
if (Math.abs(valArray[i]) > Math.abs(mostExtremeSal)) {
mostExtremeSal = valArray[i];
}
}
moreButton.style(
'background',
this.showSaliency
? () => this.getColorForSaliency(mostExtremeSal)
: () => noAttributionColor
);
}
}
},
/**
* Updates the saliency coloring of the sequential features when the current
* sequence number changes.
*/
newSeqNum: function() {
this.seqSaliency();
},
seqSaliency: function() {
if (
!this.seqFeaturesList ||
!this.saliency ||
Object.keys(this.saliency).length === 0 ||
!this.colors
) {
return;
}
// TODO(jwexler): Find a way to do this without requestAnimationFrame.
// If the paper-inputs for the features have yet to be rendered, wait to
// perform this processing.
if (this.selectAll('.value input').size() < this.seqFeaturesList.length) {
requestAnimationFrame(() => this.seqSaliency());
return;
}
// Color the text of each input element of each feature according to the
// provided saliency information for the current sequence number.
for (const feat of this.seqFeaturesList) {
const vals: SaliencyValue[] = this.saliency[
feat.name
] as SaliencyValue[];
// If there is no saliency information for the feature, do not color it.
if (!vals) {
continue;
}
const val = vals[this.seqNumber];
const colorFn = Array.isArray(val)
? (d: {}, i: number) => this.getColorForSaliency(val[i])
: () => this.getColorForSaliency(val);
this.selectAll(`.${this.sanitizeFeature(feat.name)} input`).style(
'color',
this.showSaliency ? colorFn : () => 'black'
);
}
},
/**
* Returns a list of the feature values for a feature. If keepBytes is true
* then return the raw bytes. Otherwise convert them to a readable string.
*/
getFeatureValues: function(
feature: string,
keepBytes?: boolean,
isImage?: boolean,
compareValues?: boolean
): Array<string | number> {
const feat = compareValues
? this.compareFeatures.get(feature)
: this.features.get(feature);
if (!feat) {
return [];
}
if (feat.getBytesList()) {
if (!keepBytes) {
const vals = feat
.getBytesList()!
.getValueList_asU8()
.map((u8array) => this.decodeBytesListString(u8array, isImage));
return vals;
}
return feat
.getBytesList()!
.getValueList()
.slice();
} else if (feat.getInt64List()) {
return feat
.getInt64List()!
.getValueList()
.slice();
} else if (feat.getFloatList()) {
return feat
.getFloatList()!
.getValueList()
.slice();
}
return [];
},
/**
* Returns a list of the feature values for a the compared example for
* a feature.
*/
getCompareFeatureValues: function(
feature: string,
keepBytes?: boolean,
isImage?: boolean
): Array<string | number> {
return this.getFeatureValues(feature, keepBytes, isImage, true);
},
/** Returns the first feature value for a feature. */
getFirstFeatureValue: function(feature: string) {
return this.getFeatureValues(feature)[0];
},
/** Returns the first feature value for a compared example for a feature. */
getFirstCompareFeatureValue: function(feature: string) {
return this.getCompareFeatureValues(feature)[0];
},
/** Returns if a feature has more than one feature value. */
featureHasMultipleValues: function(feature: string) {
return this.getFeatureValues(feature).length > 1;
},
/**
* Returns if a feature has more than one feature value in the compared
* example.
*/
compareFeatureHasMultipleValues: function(feature: string) {
return this.getCompareFeatureValues(feature).length > 1;
},
/**
* Returns a list of the sequence feature values for a feature for a given
* sequence number. If keepBytes is true then return the raw bytes. Otherwise
* convert them to a readable string.
*/
getSeqFeatureValues: function(
feature: string,
seqNum: number,
keepBytes?: boolean,
isImage?: boolean,
compareValues?: boolean
) {
const featlistholder = compareValues
? this.compareSeqFeatures!.get(feature)
: this.seqFeatures!.get(feature);
if (!featlistholder) {
return [];
}
const featlist = featlistholder.getFeatureList();
// It is possible that there are features that do not have sequence lengths
// as long as the longest sequence length in the example. In this case,
// show an empty feature value list for that feature.
if (!featlist || featlist.length <= seqNum) {
return [];
}
const feat = featlist[seqNum];
if (!feat) {
return [];
}
if (feat.getBytesList()) {
if (!keepBytes) {
return feat
.getBytesList()!
.getValueList_asU8()
.map((u8array) => this.decodeBytesListString(u8array, isImage));
}
return feat.getBytesList()!.getValueList();
} else if (feat.getInt64List()) {
return feat.getInt64List()!.getValueList();
} else if (feat.getFloatList()) {
return feat.getFloatList()!.getValueList();
}
return [];
},
/**
* Returns a list of the sequence feature values for a feature for a given
* sequence number of the compared example.
*/
getCompareSeqFeatureValues: function(
feature: string,
seqNum: number,
keepBytes?: boolean,
isImage?: boolean
): Array<string | number> {
return this.getSeqFeatureValues(
feature,
seqNum,
keepBytes,
isImage,
true
);
},
/** Returns the first feature value for a sequence feature. */
getFirstSeqFeatureValue: function(feature: string, seqNum: number) {
return this.getSeqFeatureValues(feature, seqNum)[0];
},
/** Returns the first feature value for the compared example for a feature. */
getFirstSeqCompareFeatureValue: function(feature: string, seqNum: number) {
return this.getCompareSeqFeatureValues(feature, seqNum)[0];
},
/** Returns if a sequence feature has more than one feature value. */
seqFeatureHasMultipleValues: function(feature: string, seqNum: number) {
return this.getSeqFeatureValues(feature, seqNum).length > 1;
},
/**
* Returns if a sequence feature has more than one feature value in the
* compared example.
*/
compareSeqFeatureHasMultipleValues: function(
feature: string,
seqNum: number
) {
return this.getCompareSeqFeatureValues(feature, seqNum).length > 1;
},
/**
* Decodes a list of bytes into a readable string, treating the bytes as
* unicode char codes. If singleByteChars is true, then treat each byte as its
* own char, which is necessary for image strings and serialized protos.
* Returns an empty string for arrays over 250MB in size, which should not
* be an issue in practice with tf.Examples.
*/
decodeBytesListString: function(
bytes: Uint8Array,
singleByteChars?: boolean
) {
if (bytes.length > MAX_BYTES_LIST_LENGTH) {
return MAX_STRING_INDICATION;
}
return singleByteChars
? this.decodeBytesListToString(bytes)
: new (window as any).TextDecoder().decode(bytes);
},
isBytesFeature: function(feature: string) {
const feat = this.features.get(feature);
if (feat) {
if (feat.hasBytesList()) {
return true;
}
}
const seqfeat = this.seqFeatures.get(feature);
if (seqfeat) {
if (seqfeat.getFeatureList()[0].hasBytesList()) {
return true;
}
}
return false;
},
/**
* Returns the feature object from the provided json attribute for a given
* feature name.
*/
getJsonFeature: function(feat: string) {
if (!this.json) {
return null;
}
if (this.json.features && this.json.features.feature) {
const jsonFeature = this.json.features.feature[feat];
if (jsonFeature) {
return jsonFeature;
}
}
if (this.json.context && this.json.context.feature) {
const jsonFeature = this.json.context.feature[feat];
if (jsonFeature) {
return jsonFeature;
}
}
if (this.json.featureLists && this.json.featureLists.featureList) {
return this.json.featureLists.featureList[feat];
}
return null;
},
/**
* Returns the value list from the provided json attribute for a given
* feature name and sequence number (when the feature is sequential). The
* sequence number should be NaN for non-sequential features.
*/
getJsonValueList: function(feat: string, seqNum: number) {
// Get the feature object for the feature name provided.
let feature = this.getJsonFeature(feat);
if (!feature) {
return null;
}
// If a sequential feature, get the feature entry for the given sequence
// number.
if (!isNaN(seqNum)) {
feature = feature.feature[seqNum];
}
const valueList =
feature.bytesList || feature.int64List || feature.floatList;
return valueList ? valueList.value : null;
},
/**
* From an element, finds the feature, value list index and sequence number
* that the element corresponds to.
*/
getDataFromElem: function(elem: HTMLElementWithData): DataFromControl {
// Get the control that contains the target data. The control will have its
// data-feature attribute set.
while (elem.dataFeature == null) {
if (!elem.parentElement) {
throw new Error('Could not find ancestor control element');
}
elem = elem.parentElement as HTMLElementWithData;
}
return {
feature: elem.dataFeature,
valueIndex: elem.dataIndex,
seqNum: elem.dataSeqNum,
};
},
/**
* From an event, finds the feature, value list index and sequence number
* that the event corresponds to.
*/
getDataFromEvent: function(event: Event): DataFromControl {
return this.getDataFromElem(event.target);
},
/** Gets the Feature object corresponding to the provided DataFromControl. */
getFeatureFromData: function(data: DataFromControl): Feature | undefined {
// If there is no sequence number, then it is a standard feature, not a
// sequential feature.
if (isNaN(data.seqNum)) {
return this.features.get(data.feature);
} else {
const featureLists = this.seqFeatures.get(data.feature);
if (!featureLists) {
return undefined;
}
const featureList = featureLists.getFeatureList();
if (!featureList) {
return undefined;
}
return featureList[data.seqNum];
}
},
/** Gets the value list corresponding to the provided DataFromControl. */
getValueListFromData: function(
data: DataFromControl
): Array<string | number> {
// If there is no sequence number, then it is a standard feature, not a
// sequential feature.
if (isNaN(data.seqNum)) {
return this.getFeatureValues(data.feature, true);
} else {
return this.getSeqFeatureValues(data.feature, data.seqNum, true);
}
},
/** Sets the value list on the provided feature. */
setFeatureValues: function(feat: Feature, values: Array<string | number>) {
const bytesList = feat.getBytesList();
const int64List = feat.getInt64List();
const floatList = feat.getFloatList();
if (bytesList) {
bytesList.setValueList(values as string[]);
} else if (int64List) {
int64List.setValueList(values as number[]);
} else if (floatList) {
floatList.setValueList(values as number[]);
}
},
/**
* When a feature value changes from a paper-input, updates the example proto
* appropriately.
*/
onValueChanged: function(event: Event) {
const inputControl = event.target as HTMLInputElement;
const data = this.getDataFromEvent(event);
const feat = this.getFeatureFromData(data);
const values = this.getValueListFromData(data);
if (feat) {
if (this.isBytesFeature(data.feature)) {
// For string features, convert the string into the char code array
// for storage in the proto.
const cc = this.stringToUint8Array(inputControl.value);
// tslint:disable-next-line:no-any cast due to tf.Example typing.
values[data.valueIndex] = cc as any;
// If the example was provided as json, update the byteslist in the
// json with the base64 encoded string. For non-bytes features we don't
// need this separate json update as the proto value list is the same
// as the json value list for that case (shallow copy). The byteslist
// case is different as the json base64 encoded string is converted to
// a list of bytes, one per character.
const jsonList = this.getJsonValueList(data.feature, data.seqNum);
if (jsonList) {
jsonList[data.valueIndex] = btoa(inputControl.value);
}
} else {
values[data.valueIndex] = +inputControl.value;
const jsonList = this.getJsonValueList(data.feature, data.seqNum);
if (jsonList) {
jsonList[data.valueIndex] = +inputControl.value;
}
}
this.setFeatureValues(feat, values);
this.exampleChanged();
}
},
onInputFocus: function(event: Event) {
const inputControl = event.target as HTMLInputElement;
const data = this.getDataFromEvent(event);
this.focusedFeatureName = data.feature;
this.focusedFeatureValueIndex = data.valueIndex;
this.focusedSeqNumber = data.seqNum;
this.$.deletevalue.style.top =
inputControl.getBoundingClientRect().top -
this.getBoundingClientRect().top -
25 +
'px';
this.$.deletevalue.style.right =
this.getBoundingClientRect().right -
inputControl.getBoundingClientRect().right +
30 +
'px';
this.showDeleteValueButton = true;
},
onInputBlur: function(event: Event) {
this.showDeleteValueButton = false;
},
/**
* When a feature is deleted, updates the example proto appropriately.
*/
deleteFeature: function(event: Event) {
const data = this.getDataFromEvent(event);
if (this.features.del) {
this.features.del(data.feature);
}
if (this.seqFeatures.del) {
this.seqFeatures.del(data.feature);
}
this.deleteJsonFeature(data.feature);
this.exampleChanged();
this.refreshExampleViewer();
},
/**
* Helper method to delete a feature from the JSON version of the example,
* if the example was provided as JSON.
*/
deleteJsonFeature: function(feature: string) {
if (this.json) {
if (this.json.features && this.json.features.feature) {
delete this.json.features.feature[feature];
}
if (this.json.context && this.json.context.feature) {
delete this.json.context.feature[feature];
}