aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx
blob: 1cc1f59dcd90abafd7820033b9f40466dfce601b (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
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { IconButton, Size } from 'browndash-components';
import * as faceapi from 'face-api.js';
import { FaceMatcher } from 'face-api.js';
import 'ldrs/ring';
import { action, makeObservable, observable } from 'mobx';
import { observer } from 'mobx-react';
import React from 'react';
import { setupMoveUpEvents } from '../../../../ClientUtils';
import { Utils, emptyFunction } from '../../../../Utils';
import { Doc, Opt } from '../../../../fields/Doc';
import { Id } from '../../../../fields/FieldSymbols';
import { List } from '../../../../fields/List';
import { ImageCast } from '../../../../fields/Types';
import { DocumentType } from '../../../documents/DocumentTypes';
import { Docs } from '../../../documents/Documents';
import { DragManager } from '../../../util/DragManager';
import { dropActionType } from '../../../util/DropActionTypes';
import { SnappingManager } from '../../../util/SnappingManager';
import { undoable } from '../../../util/UndoManager';
import { ViewBoxBaseComponent } from '../../DocComponent';
import { ObservableReactComponent } from '../../ObservableReactComponent';
import { DocumentView } from '../../nodes/DocumentView';
import { FieldView, FieldViewProps } from '../../nodes/FieldView';
import { FaceRecognitionHandler } from '../../search/FaceRecognitionHandler';
import './FaceCollectionBox.scss';
import { MarqueeOptionsMenu } from './MarqueeOptionsMenu';

/**
 * 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.
 */

interface UniqueFaceProps {
    faceDoc: Doc;
}

/**
 * React component for rendering a unique face and its collection of image Docs.
 *
 * 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 UniqueFaceView extends ObservableReactComponent<UniqueFaceProps> {
    private _dropDisposer?: DragManager.DragDropDisposer;

    constructor(props: UniqueFaceProps) {
        super(props);
        makeObservable(this);
    }

    @observable _displayImages: boolean = true;

    protected createDropTarget = (ele: HTMLDivElement) => {
        this._dropDisposer?.();
        ele && (this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this._props.faceDoc));
    };

    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._props.faceDoc).length === 0 && FaceRecognitionHandler.ImageDocFaceDescriptors(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._props.faceDoc).map(fd => new Float32Array(Array.from(fd)));
                    const labeledFaceDescriptor = new faceapi.LabeledFaceDescriptors(FaceRecognitionHandler.UniqueFaceLabel(this._props.faceDoc), faceDescriptorsAsFloat32Array);
                    const faceMatcher = new FaceMatcher([labeledFaceDescriptor], 1);
                    const { face_match } = FaceRecognitionHandler.ImageDocFaceDescriptors(imgDoc).reduce(
                        (prev, face) => {
                            const match = faceMatcher.matchDescriptor(new Float32Array(Array.from(face)));
                            return match.distance < prev.dist ? { dist: match.distance, face_match: face } : prev;
                        },
                        { dist: 1, face_match: undefined as Opt<List<number>> }
                    );

                    // assign the face in the image that's closest to the face collection to be the face that's assigned to the collection
                    if (face_match) {
                        FaceRecognitionHandler.UniqueFaceAddFaceImage(imgDoc, face_match, this._props.faceDoc);
                    }
                }
            });
        return false;
    }

    /**
     * Toggles whether a Face Document displays its associated docs.
     */
    @action
    onDisplayClick() {
        this._displayImages = !this._displayImages;
    }

    /**
     * Removes a unique face Doc from the colelction of unique faces.
     */
    deleteUniqueFace = undoable(() => {
        FaceRecognitionHandler.DeleteUniqueFace(this._props.faceDoc);
    }, '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._props.faceDoc);
    }, 'remove doc from face');

    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">
                    <h1>{FaceRecognitionHandler.UniqueFaceLabel(this._props.faceDoc)}</h1>
                </div>
                <IconButton
                    tooltip="See image information"
                    onPointerDown={() => this.onDisplayClick()}
                    icon={<FontAwesomeIcon icon={this._displayImages ? 'caret-up' : 'caret-down'} />}
                    color={MarqueeOptionsMenu.Instance.userColor}
                    style={{ width: '19px' }}
                />
                {this._displayImages ? (
                    <div className="face-document-image-container">
                        {FaceRecognitionHandler.UniqueFaceImages(this._props.faceDoc).map(doc => {
                            const [name, type] = ImageCast(doc[Doc.LayoutFieldKey(doc)]).url.href.split('.');
                            return (
                                <div
                                    className="image-wrapper"
                                    key={Utils.GenerateGuid()}
                                    onPointerDown={e =>
                                        setupMoveUpEvents(
                                            this,
                                            e,
                                            () => {
                                                DragManager.StartDocumentDrag([e.target as HTMLElement], new DragManager.DocumentDragData([doc], dropActionType.embed), e.clientX, e.clientY);
                                                return true;
                                            },
                                            emptyFunction,
                                            emptyFunction
                                        )
                                    }>
                                    <img onClick={() => 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.  Each Face collection Doc is rendered using a FaceCollectionDocView which
 * is not a CollectionView or even a DocumentView (but probably should be).
 */
@observer
export class FaceCollectionBox extends ViewBoxBaseComponent<FieldViewProps>() {
    public static LayoutString(fieldKey: string) {
        return FieldView.LayoutString(FaceCollectionBox, fieldKey);
    }

    constructor(props: FieldViewProps) {
        super(props);
        makeObservable(this);
    }

    render() {
        return (
            <div className="searchBox-container" style={{ pointerEvents: 'all', color: SnappingManager.userColor, background: SnappingManager.userBackgroundColor }}>
                {FaceRecognitionHandler.UniqueFaces().map(doc => (
                    <UniqueFaceView key={doc[Id]} faceDoc={doc} />
                ))}
            </div>
        );
    }
}

Docs.Prototypes.TemplateMap.set(DocumentType.FACECOLLECTION, {
    layout: { view: FaceCollectionBox, dataField: 'data' },
    options: { acl: '', _width: 400 },
});