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
|
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { IconButton, Size } from '@dash/components';
import * as faceapi from 'face-api.js';
import { FaceMatcher } from 'face-api.js';
import 'ldrs/ring';
import { IReactionDisposer, action, makeObservable, observable, reaction } from 'mobx';
import { observer } from 'mobx-react';
import React from 'react';
import { DivHeight, lightOrDark, returnTrue, setupMoveUpEvents } from '../../../../ClientUtils';
import { emptyFunction } from '../../../../Utils';
import { Doc, DocListCast, Opt } from '../../../../fields/Doc';
import { DocData } from '../../../../fields/DocSymbols';
import { List } from '../../../../fields/List';
import { DocCast, ImageCastToNameType, NumCast, StrCast } from '../../../../fields/Types';
import { DocumentType } from '../../../documents/DocumentTypes';
import { Docs } from '../../../documents/Documents';
import { DragManager } from '../../../util/DragManager';
import { dropActionType } from '../../../util/DropActionTypes';
import { undoable } from '../../../util/UndoManager';
import { ViewBoxBaseComponent } from '../../DocComponent';
import { DocumentView } from '../../nodes/DocumentView';
import { FieldView, FieldViewProps } from '../../nodes/FieldView';
import { FaceRecognitionHandler } from '../../search/FaceRecognitionHandler';
import { CollectionStackingView } from '../CollectionStackingView';
import './FaceCollectionBox.scss';
import { MarqueeOptionsMenu } from './MarqueeOptionsMenu';
import { returnEmptyDocViewList } from '../../StyleProvider';
/**
* This code is used to render the sidebar collection of unique recognized faces, where each
* unique face in turn displays the set of images that correspond to the face.
*/
/**
* Viewer for unique face Doc collections.
*
* This both displays a collection of images corresponding tp a unique face, and
* allows for editing the face collection by removing an image, or drag-and-dropping
* an image that was not recognized.
*/
@observer
export class UniqueFaceBox extends ViewBoxBaseComponent<FieldViewProps>() {
public static LayoutString(fieldKey: string) {
return FieldView.LayoutString(UniqueFaceBox, fieldKey);
}
private _dropDisposer?: DragManager.DragDropDisposer;
private _disposers: { [key: string]: IReactionDisposer } = {};
private _lastHeight = 0;
constructor(props: FieldViewProps) {
super(props);
makeObservable(this);
}
@observable _headerRef: HTMLDivElement | null = null;
@observable _listRef: HTMLDivElement | null = null;
observer = new ResizeObserver(() => {
this._props.setHeight?.(
(this.props.Document._face_showImages ? 20 : 0) + //
(!this._headerRef ? 0 : DivHeight(this._headerRef)) +
(!this._listRef ? 0 : DivHeight(this._listRef))
);
});
componentDidMount(): void {
this._disposers.refList = reaction(
() => ({ refList: [this._headerRef, this._listRef], autoHeight: this.layoutDoc._layout_autoHeight }),
({ refList, autoHeight }) => {
this.observer.disconnect();
if (autoHeight) refList.filter(r => r).forEach(r => this.observer.observe(r!));
},
{ fireImmediately: true }
);
}
componentWillUnmount(): void {
this.observer.disconnect();
Object.keys(this._disposers).forEach(key => this._disposers[key]());
}
protected createDropTarget = (ele: HTMLDivElement) => {
this._dropDisposer?.();
ele && (this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.Document));
};
protected onInternalDrop(e: Event, de: DragManager.DropEvent): boolean {
de.complete.docDragData?.droppedDocuments
?.filter(doc => doc.type === DocumentType.IMG)
.forEach(imgDoc => {
// If the current Face Document has no faces, and the doc has more than one face descriptor, don't let the user add the document first. Or should we just use the first face ?
if (FaceRecognitionHandler.UniqueFaceDescriptors(this.Document).length === 0 && FaceRecognitionHandler.ImageDocFaceAnnos(imgDoc).length > 1) {
alert('Cannot add a document with multiple faces as the first item!');
} else {
// Loop through the documents' face descriptors and choose the face in the iage with the smallest distance (most similar to the face colleciton)
const faceDescriptorsAsFloat32Array = FaceRecognitionHandler.UniqueFaceDescriptors(this.Document).map(fd => new Float32Array(Array.from(fd)));
const labeledFaceDescriptor = new faceapi.LabeledFaceDescriptors(FaceRecognitionHandler.UniqueFaceLabel(this.Document), faceDescriptorsAsFloat32Array);
const faceMatcher = new FaceMatcher([labeledFaceDescriptor], 1);
const faceAnno =
FaceRecognitionHandler.ImageDocFaceAnnos(imgDoc).reduce(
(prev, fAnno) => {
const match = faceMatcher.matchDescriptor(new Float32Array(Array.from(fAnno.faceDescriptor as List<number>)));
return match.distance < prev.dist ? { dist: match.distance, faceAnno: fAnno } : prev;
},
{ dist: 1, faceAnno: undefined as Opt<Doc> }
).faceAnno ?? imgDoc;
// assign the face in the image that's closest to the face collection's face
if (faceAnno) {
DocCast(faceAnno.face) && FaceRecognitionHandler.UniqueFaceRemoveFaceImage(faceAnno, DocCast(faceAnno.face)!);
FaceRecognitionHandler.UniqueFaceAddFaceImage(faceAnno, this.Document);
faceAnno.$face = this.Document[DocData];
}
}
});
de.complete.docDragData?.droppedDocuments
?.filter(doc => DocCast(doc.face)?.type === DocumentType.UFACE)
.forEach(faceAnno => {
const imgDoc = faceAnno;
DocCast(faceAnno.face) && FaceRecognitionHandler.UniqueFaceRemoveFaceImage(imgDoc, DocCast(faceAnno.face)!);
FaceRecognitionHandler.UniqueFaceAddFaceImage(faceAnno, this.Document);
faceAnno.$face = this.Document[DocData];
});
e.stopPropagation();
return true;
}
/**
* Toggles whether a Face Document displays its associated docs. This saves and restores the last height of the Doc since
* toggling the associated Documentss overwrites the Doc height.
*/
onDisplayClick() {
this.Document._face_showImages && (this._lastHeight = NumCast(this.Document.height));
this.Document._face_showImages = !this.Document._face_showImages;
setTimeout(action(() => (!this.Document.layout_autoHeight || !this.Document._face_showImages) && (this.Document.height = this.Document._face_showImages ? this._lastHeight : 60)));
}
/**
* Removes a unique face Doc from the colelction of unique faces.
*/
deleteUniqueFace = undoable(() => {
FaceRecognitionHandler.DeleteUniqueFace(this.Document);
}, 'delete face');
/**
* Removes a face image Doc from a unique face's list of images.
* @param imgDoc - image Doc to remove
*/
removeFaceImageFromUniqueFace = undoable((imgDoc: Doc) => {
FaceRecognitionHandler.UniqueFaceRemoveFaceImage(imgDoc, this.Document);
}, 'remove doc from face');
setRef = (r: HTMLDivElement | null) => this.fixWheelEvents(r, this._props.isContentActive);
render() {
return (
<div className="face-document-item" ref={ele => this.createDropTarget(ele!)}>
<div className="face-collection-buttons">
<IconButton tooltip="Delete Face From Collection" onPointerDown={this.deleteUniqueFace} icon={'x'} style={{ width: '4px' }} size={Size.XSMALL} />
</div>
<div className="face-document-top" ref={action((r: HTMLDivElement | null) => (this._headerRef = r))}>
<h1 style={{ color: lightOrDark(StrCast(this.Document.backgroundColor)) }}>
<input className="face-document-name" type="text" onChange={e => FaceRecognitionHandler.SetUniqueFaceLabel(this.Document, e.currentTarget.value)} value={FaceRecognitionHandler.UniqueFaceLabel(this.Document)} />
</h1>
</div>
<div className="face-collection-toggle">
<IconButton
tooltip="See image information"
onPointerDown={() => this.onDisplayClick()}
icon={<FontAwesomeIcon icon={this.Document._face_showImages ? 'caret-up' : 'caret-down'} />}
color={MarqueeOptionsMenu.Instance.userColor}
style={{ width: '19px' }}
/>
</div>
{this.props.Document._face_showImages ? (
<div
className="face-document-image-container"
style={{
pointerEvents: this._props.isContentActive() ? undefined : 'none',
}}
ref={this.setRef}>
{FaceRecognitionHandler.UniqueFaceImages(this.Document).map((doc, i) => {
const [name, type] = ImageCastToNameType(doc?.[Doc.LayoutDataKey(doc)]) ?? ['-missing-', '.png'];
return (
<div
className="image-wrapper"
key={i}
onPointerDown={e =>
setupMoveUpEvents(
this,
e,
() => {
const dragDoc = DocListCast(doc?.data_annotations).find(a => a.face === this.Document[DocData]) ?? this.Document;
DragManager.StartDocumentDrag([e.target as HTMLElement], new DragManager.DocumentDragData([dragDoc], dropActionType.embed), e.clientX, e.clientY);
return true;
},
emptyFunction,
emptyFunction
)
}>
<img onClick={() => doc && DocumentView.showDocument(doc, { willZoomCentered: true })} style={{ maxWidth: '60px', margin: '10px' }} src={`${name}_o.${type}`} />
<div className="remove-item">
<IconButton tooltip={'Remove Doc From Face Collection'} onPointerDown={() => this.removeFaceImageFromUniqueFace(doc)} icon={'x'} style={{ width: '4px' }} size={Size.XSMALL} />
</div>
</div>
);
})}
</div>
) : null}
</div>
);
}
}
/**
* This renders the sidebar collection of the unique faces that have been recognized.
*
* Since the collection of recognized faces is stored on the active dashboard, this class
* does not itself store any Docs, but accesses the myUniqueFaces field of the current
* dashboard. (This should probably go away as Doc type in favor of it just being a
* stacking collection of uniqueFace docs)
*/
@observer
export class FaceCollectionBox extends ViewBoxBaseComponent<FieldViewProps>() {
public static LayoutString(fieldKey: string) {
return FieldView.LayoutString(FaceCollectionBox, fieldKey);
}
constructor(props: FieldViewProps) {
super(props);
makeObservable(this);
}
moveDocument = (doc: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (doc: Doc | Doc[]) => boolean): boolean => !!(this._props.removeDocument?.(doc) && addDocument?.(doc));
// eslint-disable-next-line @typescript-eslint/no-unused-vars
addDocument = (doc: Doc | Doc[], annotationKey?: string) => {
const uniqueFaceDoc = doc instanceof Doc ? doc : doc[0];
const added = uniqueFaceDoc.type === DocumentType.UFACE;
if (added) {
Doc.MyFaceCollection && Doc.SetContainer(uniqueFaceDoc, Doc.MyFaceCollection);
Doc.ActiveDashboard && Doc.AddDocToList(Doc.ActiveDashboard[DocData], 'myUniqueFaces', uniqueFaceDoc);
}
return added;
};
/**
* this changes style provider requests that target the dashboard to requests that target the face collection box which is what's actually being rendered.
* This is needed, for instance, to get the default background color from the face collection, not the dashboard.
*/
stackingStyleProvider = (doc: Doc | undefined, props: Opt<FieldViewProps>, property: string) => {
if (doc === Doc.ActiveDashboard) return this._props.styleProvider?.(this.Document, this._props, property);
return this._props.styleProvider?.(doc, this._props, property);
};
render() {
return !Doc.ActiveDashboard ? null : (
<div className="faceCollectionBox">
<div className="documentButtonMenu">
<div className="documentExplanation" onClick={action(() => (Doc.UserDoc().recognizeFaceImages = !Doc.UserDoc().recognizeFaceImages))}>{`Face Recgognition is ${Doc.UserDoc().recognizeFaceImages ? 'on' : 'off'}`}</div>
</div>
<CollectionStackingView
{...this._props} //
styleProvider={this.stackingStyleProvider}
Document={Doc.ActiveDashboard}
DocumentView={undefined}
docViewPath={returnEmptyDocViewList}
fieldKey="myUniqueFaces"
moveDocument={this.moveDocument}
addDocument={this.addDocument}
isContentActive={returnTrue}
isAnyChildContentActive={returnTrue}
childHideDecorations={true}
dontCenter="y"
/>
</div>
);
}
}
Docs.Prototypes.TemplateMap.set(DocumentType.FACECOLLECTION, {
layout: { view: FaceCollectionBox, dataField: 'data' },
options: { acl: '', _width: 400, dropAction: dropActionType.embed },
});
Docs.Prototypes.TemplateMap.set(DocumentType.UFACE, {
layout: { view: UniqueFaceBox, dataField: 'face_images' },
options: { acl: '', _width: 400, _height: 400 },
});
|