aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx
diff options
context:
space:
mode:
authoreleanor-park <eleanor_park@brown.edu>2024-08-27 16:44:12 -0400
committereleanor-park <eleanor_park@brown.edu>2024-08-27 16:44:12 -0400
commit39d2bba7bf4b0cc3759931691640083a48cce662 (patch)
tree8bf110760aa926237b6294aec545f48cfc92747d /src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx
parent6f73686ec4dc3e01ae3eacc0150aa59eafea0325 (diff)
parentb8a04a0fedf8ef3612395764a0ecd01f6824ebd1 (diff)
Merge branch 'master' into eleanor-gptdraw
Diffstat (limited to 'src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx')
-rw-r--r--src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx280
1 files changed, 280 insertions, 0 deletions
diff --git a/src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx b/src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx
new file mode 100644
index 000000000..c62303dc0
--- /dev/null
+++ b/src/client/views/collections/collectionFreeForm/FaceCollectionBox.tsx
@@ -0,0 +1,280 @@
+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 { 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, Opt } from '../../../../fields/Doc';
+import { DocData } from '../../../../fields/DocSymbols';
+import { List } from '../../../../fields/List';
+import { DocCast, ImageCast, 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';
+
+/**
+ * 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(a => {
+ 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, faceAnno) => {
+ const match = faceMatcher.matchDescriptor(new Float32Array(Array.from(faceAnno.faceDescriptor as List<number>)));
+ return match.distance < prev.dist ? { dist: match.distance, faceAnno } : prev;
+ },
+ { dist: 1, faceAnno: undefined as Opt<Doc> }
+ );
+
+ // assign the face in the image that's closest to the face collection's face
+ if (faceAnno) {
+ FaceRecognitionHandler.UniqueFaceRemoveFaceImage(faceAnno, DocCast(faceAnno.face));
+ FaceRecognitionHandler.UniqueFaceAddFaceImage(faceAnno, this.Document);
+ faceAnno.face = this.Document;
+ }
+ }
+ });
+ 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');
+
+ /**
+ * This stops scroll wheel events when they are used to scroll the face collection.
+ */
+ onPassiveWheel = (e: WheelEvent) => e.stopPropagation();
+
+ 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={action((ele: HTMLDivElement | null) => {
+ this._listRef?.removeEventListener('wheel', this.onPassiveWheel);
+ this._listRef = ele;
+ // prevent wheel events from passively propagating up through containers and prevents containers from preventDefault which would block scrolling
+ ele?.addEventListener('wheel', this.onPassiveWheel, { passive: false });
+ })}>
+ {FaceRecognitionHandler.UniqueFaceImages(this.Document).map((doc, i) => {
+ const [name, type] = ImageCast(doc[Doc.LayoutFieldKey(doc)]).url.href.split('.');
+ return (
+ <div
+ className="image-wrapper"
+ key={i}
+ 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. (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));
+ addDocument = (doc: Doc | Doc[], annotationKey?: string) => {
+ const uniqueFaceDoc = doc instanceof Doc ? doc : doc[0];
+ const added = uniqueFaceDoc.type === DocumentType.UFACE;
+ if (added) {
+ 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}
+ fieldKey="myUniqueFaces"
+ moveDocument={this.moveDocument}
+ addDocument={this.addDocument}
+ isContentActive={returnTrue}
+ isAnyChildContentActive={returnTrue}
+ childHideDecorations={true}
+ />
+ </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 },
+});