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
|
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Colors, IconButton } from '@dash/components';
import similarity from 'compute-cosine-similarity';
import { ring } from 'ldrs';
import 'ldrs/ring';
import { action, computed, makeObservable, observable, reaction } from 'mobx';
import { observer } from 'mobx-react';
import React from 'react';
import { imageUrlToBase64 } from '../../../../ClientUtils';
import { Utils, numberRange } from '../../../../Utils';
import { Doc, NumListCast, Opt } from '../../../../fields/Doc';
import { List } from '../../../../fields/List';
import { ImageCastToNameType, ImageCastWithSuffix } from '../../../../fields/Types';
import { gptGetEmbedding, gptImageLabel } from '../../../apis/gpt/GPT';
import { DocumentType } from '../../../documents/DocumentTypes';
import { Docs } from '../../../documents/Documents';
import { DragManager } from '../../../util/DragManager';
import { SettingsManager } from '../../../util/SettingsManager';
import { SnappingManager } from '../../../util/SnappingManager';
import { ViewBoxBaseComponent } from '../../DocComponent';
import { MainView } from '../../MainView';
import { DocumentView } from '../../nodes/DocumentView';
import { FieldView, FieldViewProps } from '../../nodes/FieldView';
import { OpenWhere } from '../../nodes/OpenWhere';
import './ImageLabelBox.scss';
import { MarqueeOptionsMenu } from './MarqueeOptionsMenu';
export class ImageInformationItem {}
export class ImageLabelBoxData {
// eslint-disable-next-line no-use-before-define
static _instance: ImageLabelBoxData;
@observable _docs: Doc[] = [];
@observable _labelGroups: string[] = [];
constructor() {
makeObservable(this);
ImageLabelBoxData._instance = this;
}
public static get Instance() {
return ImageLabelBoxData._instance ?? new ImageLabelBoxData();
}
@action
public setData = (docs: Doc[]) => {
this._docs = docs;
};
@action
addLabel = (labelIn: string) => {
const label = labelIn.toUpperCase().trim();
if (label.length > 0) {
if (!this._labelGroups.includes(label)) {
this._labelGroups = [...this._labelGroups, label.startsWith('#') ? label : '#' + label];
}
}
};
@action
removeLabel = (label: string) => {
const labelUp = label.toUpperCase();
this._labelGroups = this._labelGroups.filter(group => group !== labelUp);
};
}
@observer
export class ImageLabelBox extends ViewBoxBaseComponent<FieldViewProps>() {
public static LayoutString(fieldKey: string) {
return FieldView.LayoutString(ImageLabelBox, fieldKey);
}
// eslint-disable-next-line no-use-before-define
public static Instance: ImageLabelBox;
private _dropDisposer?: DragManager.DragDropDisposer;
private _inputRef = React.createRef<HTMLInputElement>();
@observable _loading: boolean = false;
private _currentLabel: string = '';
protected createDropTarget = (ele: HTMLDivElement) => {
this._dropDisposer?.();
ele && (this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.layoutDoc));
};
protected onInternalDrop(e: Event, de: DragManager.DropEvent): boolean {
const { docDragData } = de.complete;
if (docDragData) {
ImageLabelBoxData.Instance.setData(ImageLabelBoxData.Instance._docs.concat(docDragData.droppedDocuments));
return false;
}
return false;
}
@computed get _labelGroups() {
return ImageLabelBoxData.Instance._labelGroups;
}
@computed get _selectedImages() {
// return DocListCast(this.dataDoc.data);
return ImageLabelBoxData.Instance._docs;
}
@observable _displayImageInformation: boolean = false;
constructor(props: FieldViewProps) {
super(props);
makeObservable(this);
ring.register();
ImageLabelBox.Instance = this;
}
// ImageLabelBox.Instance.setData()
/**
* This method is called when the SearchBox component is first mounted. When the user opens
* the search panel, the search input box is automatically selected. This allows the user to
* type in the search input box immediately, without needing clicking on it first.
*/
componentDidMount() {
this.classifyImagesInBox();
reaction(
() => this._selectedImages,
() => this.classifyImagesInBox()
);
}
@action
groupImages = () => {
this.groupImagesInBox();
};
@action
startLoading = () => {
this._loading = true;
};
@action
endLoading = () => {
this._loading = false;
};
@action
toggleDisplayInformation = () => {
this._displayImageInformation = !this._displayImageInformation;
if (this._displayImageInformation) {
this._selectedImages.forEach(doc => (doc._layout_showTags = true));
} else {
this._selectedImages.forEach(doc => (doc._layout_showTags = false));
}
};
@action
submitLabel = () => {
const input = document.getElementById('new-label') as HTMLInputElement;
ImageLabelBoxData.Instance.addLabel(this._currentLabel);
this._currentLabel = '';
input.value = '';
};
onInputChange = action((e: React.ChangeEvent<HTMLInputElement>) => {
this._currentLabel = e.target.value;
});
classifyImagesInBox = async () => {
this.startLoading();
// Converts the images into a Base64 format, afterwhich the information is sent to GPT to label them.
const imageInfos = this._selectedImages.map(async doc => {
if (!doc.$tags_chat) {
const url = ImageCastWithSuffix(doc[Doc.LayoutDataKey(doc)], '_o') ?? '';
return imageUrlToBase64(url).then(hrefBase64 =>
!hrefBase64 ? undefined :
gptImageLabel(hrefBase64,'Give three labels to describe this image.').then(labels =>
({ doc, labels }))) ; // prettier-ignore
}
});
(await Promise.all(imageInfos)).forEach(imageInfo => {
if (imageInfo) {
imageInfo.doc.$tags_chat = (imageInfo.doc.$tags_chat as List<string>) ?? new List<string>();
const labels = imageInfo.labels.split('\n');
labels.forEach(label => {
const hashLabel =
'#' +
label
.replace(/^\d+\.\s*|-|f\*/, '')
.replace(/^#/, '')
.trim();
(imageInfo.doc.$tags_chat as List<string>).push(hashLabel);
});
}
});
this.endLoading();
};
/**
* Groups images to most similar labels.
*/
groupImagesInBox = action(async () => {
this.startLoading();
await Promise.all(
this._selectedImages
.map(doc => ({ doc, labels: doc.$tags_chat as List<string> }))
.map(({ doc, labels }) => labels.map((label, index) => gptGetEmbedding(label).then(embedding => (doc[`$tags_embedding_${index + 1}`] = new List<number>(embedding)))))
);
const labelToEmbedding = new Map<string, number[]>();
// Create embeddings for the labels.
await Promise.all(this._labelGroups.map(async label => gptGetEmbedding(label).then(labelEmbedding => labelToEmbedding.set(label, labelEmbedding))));
// For each image, loop through the labels, and calculate similarity. Associate it with the
// most similar one.
this._selectedImages.forEach(doc => {
const embedLists = numberRange((doc.$tags_chat as List<string>).length).map(n => Array.from(NumListCast(doc[`$tags_embedding_${n + 1}`])));
const bestEmbedScore = (embedding: Opt<number[]>) => Math.max(...embedLists.map(l => (embedding && similarity(Array.from(embedding), l)!) || 0));
const {label: mostSimilarLabelCollect} =
this._labelGroups.map(label => ({ label, similarityScore: bestEmbedScore(labelToEmbedding.get(label)) }))
.reduce((prev, cur) => cur.similarityScore < 0.3 || cur.similarityScore <= prev.similarityScore ? prev: cur,
{ label: '', similarityScore: 0, }); // prettier-ignore
doc.$data_label = mostSimilarLabelCollect; // The label most similar to the image's contents.
});
this.endLoading();
if (this._selectedImages) {
MarqueeOptionsMenu.Instance.groupImages();
}
MainView.Instance.closeFlyout();
});
render() {
if (this._loading) {
return (
<div className="image-box-container" style={{ pointerEvents: 'all', color: SnappingManager.userColor, background: SnappingManager.userBackgroundColor }}>
<l-ring size="60" color="white" />
</div>
);
}
if (this._selectedImages.length === 0) {
return (
<div className="searchBox-container" style={{ pointerEvents: 'all', color: SnappingManager.userColor, background: SnappingManager.userBackgroundColor }} ref={ele => this.createDropTarget(ele!)}>
<p style={{ fontSize: 'large' }}>In order to classify and sort images, marquee select the desired images and press the 'Classify and Sort Images' button. Then, add the desired groups for the images to be put in.</p>
</div>
);
}
return (
<div className="searchBox-container" style={{ pointerEvents: 'all', color: SnappingManager.userColor, background: SnappingManager.userBackgroundColor }} ref={ele => this.createDropTarget(ele!)}>
<div className="searchBox-bar" style={{ pointerEvents: 'all', color: SnappingManager.userColor, background: SnappingManager.userBackgroundColor }}>
<IconButton
tooltip={'See image information'}
onPointerDown={this.toggleDisplayInformation}
icon={this._displayImageInformation ? <FontAwesomeIcon icon="caret-up" /> : <FontAwesomeIcon icon="caret-down" />}
color={MarqueeOptionsMenu.Instance.userColor}
style={{ width: '19px' }}
/>
<input
defaultValue=""
autoComplete="off"
onChange={this.onInputChange}
onKeyDown={e => {
e.key === 'Enter' ? this.submitLabel() : null;
e.stopPropagation();
}}
type="text"
placeholder="Input groups for images to be put into..."
aria-label="label-input"
id="new-label"
className="searchBox-input"
style={{ width: '100%', borderRadius: '5px' }}
ref={this._inputRef}
/>
<IconButton
tooltip={'Add a label'}
onPointerDown={() => {
const input = document.getElementById('new-label') as HTMLInputElement;
ImageLabelBoxData.Instance.addLabel(this._currentLabel);
this._currentLabel = '';
input.value = '';
}}
icon={<FontAwesomeIcon icon="plus" />}
color={MarqueeOptionsMenu.Instance.userColor}
style={{ width: '19px' }}
/>
{this._labelGroups.length > 0 ? <IconButton tooltip={'Group Images'} onPointerDown={this.groupImages} icon={<FontAwesomeIcon icon="object-group" />} color={Colors.MEDIUM_BLUE} style={{ width: '19px' }} /> : <div></div>}
</div>
<div>
<div className="image-label-list">
{this._labelGroups.map(group => {
return (
<div key={Utils.GenerateGuid()}>
<p style={{ color: MarqueeOptionsMenu.Instance.userColor }}>{group}</p>
<IconButton
tooltip={'Remove Label'}
onPointerDown={() => {
ImageLabelBoxData.Instance.removeLabel(group);
}}
icon={'x'}
color={MarqueeOptionsMenu.Instance.userColor}
style={{ width: '8px' }}
/>
</div>
);
})}
</div>
</div>
{this._displayImageInformation ? (
<div className="image-information-list">
{this._selectedImages.map(doc => {
const [name, type] = ImageCastToNameType(doc[Doc.LayoutDataKey(doc)]);
return (
<div className="image-information" style={{ borderColor: SettingsManager.userColor }} key={Utils.GenerateGuid()}>
<img
src={`${name}_o.${type}`}
onClick={async () => {
await DocumentView.showDocument(doc, { willZoomCentered: true });
}}></img>
<div className="image-information-labels" onClick={() => this._props.addDocTab(doc, OpenWhere.addRightKeyvalue)}>
{(doc.$tags_chat as List<string>).map(label => {
return (
<div key={Utils.GenerateGuid()} className="image-label" style={{ backgroundColor: SettingsManager.userVariantColor, borderColor: SettingsManager.userColor }}>
{label}
</div>
);
})}
</div>
</div>
);
})}
</div>
) : (
<div></div>
)}
</div>
);
}
}
Docs.Prototypes.TemplateMap.set(DocumentType.IMAGEGROUPER, {
layout: { view: ImageLabelBox, dataField: 'data' },
options: { acl: '', _width: 400 },
});
|