Repository navigation
Expand file tree
/
Copy pathvec_client.pas
More file actions
797 lines (706 loc) · 23.9 KB
/
Copy pathvec_client.pas
File metadata and controls
797 lines (706 loc) · 23.9 KB
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
{
VEC 2.0 Delphi Client SDK (binary frame protocol)
VEC 2.0 is a clean break from 1.x. SDKs from 1.x are not wire-compatible.
See PROTOCOL-2.0.md for the full spec.
See examples/delphi/ for relational-ID, filename-label, and sidecar-data examples.
Local transport only in this version (Windows named pipe):
\\.\pipe\vec_<name>
Usage:
var Vec: TVecClient;
var Recs: TVecRecords;
Vec := TVecClient.Create;
Vec.Connect('tools');
// Push: vector required; non-empty inline data requires a label
idx := Vec.Push(myVector);
idx := Vec.PushLabeled('img/cat.jpg', myVector);
idx := Vec.PushFull('img/cat.jpg', myVector, jpegBytes);
Recs := Vec.Query(qVec);
Recs := Vec.Query(qVec, True, VEC_SHAPE_LABEL); // cosine, lean
Recs := Vec.QID(42);
Recs := Vec.QIDByLabel('img/cat.jpg', True);
Recs := Vec.Get(42);
Recs := Vec.GetByLabel('img/cat.jpg');
Recs := Vec.GetBatch([0,1,2]);
Vec.SetData(42, jpegBytes);
blob := Vec.GetData(42);
Vec.Update(42, myVector);
Vec.SetLabel(42, 'img/cat.jpg');
Vec.Delete(42); // also clears label + data
Vec.Undo; // also clears last label + data
Vec.Save(saved, crc);
info := Vec.Info; // info.ProtocolVersion = 2
Vec.Free;
}
unit vec_client;
interface
uses
Windows, SysUtils;
const
VEC_BIN_MAGIC = $F0;
VEC_PROTOCOL_VERSION = $02;
VEC_CMD_PUSH = $01;
VEC_CMD_QUERY = $02;
VEC_CMD_GET = $04;
VEC_CMD_UPDATE = $06;
VEC_CMD_DELETE = $07;
VEC_CMD_LABEL = $08;
VEC_CMD_UNDO = $09;
VEC_CMD_SAVE = $0A;
VEC_CMD_CLUSTER = $0D;
VEC_CMD_DISTINCT = $0E;
VEC_CMD_REPRESENT = $0F;
VEC_CMD_INFO = $10;
VEC_CMD_QID = $11;
VEC_CMD_SET_DATA = $13;
VEC_CMD_GET_DATA = $14;
VEC_CMD_EXISTS = $15;
VEC_RESP_OK = $00;
VEC_RESP_ERR = $01;
VEC_SHAPE_VECTOR = $01;
VEC_SHAPE_LABEL = $02;
VEC_SHAPE_DATA = $04;
VEC_SHAPE_FULL = VEC_SHAPE_VECTOR or VEC_SHAPE_LABEL or VEC_SHAPE_DATA;
VEC_GET_MODE_SINGLE = $00;
VEC_GET_MODE_BATCH = $01;
VEC_METRIC_L2 = $00;
VEC_METRIC_COSINE = $01;
VEC_MAX_LABEL_BYTES = 2048;
VEC_MAX_DATA_BYTES = 102400;
type
TSingleArray = array of Single;
TByteArray = array of Byte;
TVecRecord = record
Index : Integer;
Distance : Single; { valid only for query/qid }
Label_ : string; { empty if shape excluded label }
Data : TByteArray; { nil if shape excluded data }
Vector : TSingleArray; { nil if shape excluded vector }
end;
TVecRecords = array of TVecRecord;
TVecExistsResult = record
Found : Boolean;
Index : Integer;
Label_ : string; { empty if shape excluded label }
Data : TByteArray; { nil if shape excluded data }
end;
TVecInfo = record
Dim : Integer;
Count : Integer;
Deleted : Integer;
Fmt : Integer; { 0=f32, 1=f16 }
MTime : Int64; { GPU last write; CPU tensor-file mtime }
CRC : Cardinal;
CRC_OK : Integer; { 0=mismatch/new, 1=ok, 255=legacy no CRC trailer }
Name : string;
ProtocolVersion : Integer;
end;
TIntArray = array of Integer;
TVecCluster = record
Members : TIntArray; { slot indices }
Centroid : TSingleArray; { arithmetic mean of member vectors, fp32 }
end;
TVecClusters = array of TVecCluster;
TVecClusterResult = record
Clusters : TVecClusters;
Noise : TIntArray;
end;
TVecClient = class
private
FConnected: Boolean;
FPipeHandle: THandle;
FNamespace: AnsiString; { reserved for router mode in a later version }
FDimCache: Integer;
procedure SendRaw(const Data: Pointer; Len: Integer);
procedure RecvExact(Buf: Pointer; Len: Integer);
procedure SendFrame(Cmd: Byte; const ALabel: AnsiString; const Body: AnsiString);
function RecvResponse: AnsiString;
function ParseRecords(const Body: AnsiString; Shape: Byte; Dim: Integer;
WithDistance: Boolean): TVecRecords;
function EnsureDim: Integer;
public
constructor Create; overload;
function Connect(const Name: string): Boolean;
function Push(const Vec: TSingleArray): Integer;
function PushLabeled(const ALabel: string; const Vec: TSingleArray): Integer;
function PushFull(const ALabel: string; const Vec: TSingleArray; const Data: TByteArray): Integer;
function Query(const Vec: TSingleArray): TVecRecords; overload;
function Query(const Vec: TSingleArray; Cosine: Boolean; Shape: Byte = VEC_SHAPE_FULL): TVecRecords; overload;
function QID(Index: Integer): TVecRecords; overload;
function QID(Index: Integer; Cosine: Boolean; Shape: Byte = VEC_SHAPE_FULL): TVecRecords; overload;
function QIDByLabel(const ALabel: string): TVecRecords; overload;
function QIDByLabel(const ALabel: string; Cosine: Boolean; Shape: Byte = VEC_SHAPE_FULL): TVecRecords; overload;
function Get(Index: Integer; Shape: Byte = VEC_SHAPE_FULL): TVecRecords;
function GetByLabel(const ALabel: string; Shape: Byte = VEC_SHAPE_FULL): TVecRecords;
function GetBatch(const Indices: array of Integer; Shape: Byte = VEC_SHAPE_FULL): TVecRecords;
function Exists(const Vec: TSingleArray; Shape: Byte = 0): TVecExistsResult;
procedure SetData(Index: Integer; const Data: TByteArray); overload;
procedure SetData(const ALabel: string; const Data: TByteArray); overload;
function GetData(Index: Integer): TByteArray; overload;
function GetData(const ALabel: string): TByteArray; overload;
procedure Update(Index: Integer; const Vec: TSingleArray);
procedure UpdateByLabel(const ALabel: string; const Vec: TSingleArray);
procedure SetLabel(Index: Integer; const ALabel: string);
procedure Delete(Index: Integer); overload;
procedure Delete(const ALabel: string); overload;
procedure Undo;
procedure Save(out SavedCount: Cardinal; out CRC: Cardinal); overload;
procedure Save; overload;
function Info: TVecInfo;
function Cluster(Eps: Single; Cosine: Boolean = False; MinPts: Integer = 2): TVecClusterResult;
function DistinctRaw(K: Integer; Cosine: Boolean = False): TArray<string>;
function RepresentRaw(Eps: Single; Cosine: Boolean = False; MinPts: Integer = 2): TArray<string>;
procedure Close;
destructor Destroy; override;
property Connected: Boolean read FConnected;
end;
implementation
constructor TVecClient.Create;
begin
inherited;
FConnected := False;
FPipeHandle := INVALID_HANDLE_VALUE;
FNamespace := '';
FDimCache := 0;
end;
function TVecClient.Connect(const Name: string): Boolean;
var
PipeName: string;
begin
Result := False;
if Name = '' then Exit;
PipeName := '\\.\pipe\vec_' + Name;
FPipeHandle := CreateFileA(PAnsiChar(AnsiString(PipeName)),
GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, 0, 0);
if FPipeHandle = INVALID_HANDLE_VALUE then Exit;
FConnected := True;
Result := True;
end;
procedure TVecClient.SendRaw(const Data: Pointer; Len: Integer);
var
Written: DWORD;
begin
if Len <= 0 then Exit;
WriteFile(FPipeHandle, Data^, Len, Written, nil);
end;
procedure TVecClient.RecvExact(Buf: Pointer; Len: Integer);
var
BytesRead: DWORD;
Got: Integer;
begin
if Len <= 0 then Exit;
Got := 0;
while Got < Len do begin
ReadFile(FPipeHandle, PAnsiChar(Buf)[Got], Len - Got, BytesRead, nil);
if BytesRead = 0 then Break;
Inc(Got, BytesRead);
end;
end;
procedure TVecClient.SendFrame(Cmd: Byte; const ALabel: AnsiString; const Body: AnsiString);
var
NS: AnsiString;
Frame: AnsiString;
NSLen, LblLen: Word;
BodyLen: Cardinal;
Off: Integer;
begin
NS := FNamespace;
NSLen := Length(NS);
LblLen := Length(ALabel);
if LblLen > VEC_MAX_LABEL_BYTES then
raise Exception.CreateFmt('label too long (%d > %d)', [LblLen, VEC_MAX_LABEL_BYTES]);
BodyLen := Length(Body);
SetLength(Frame, 1 + 2 + NSLen + 1 + 2 + LblLen + 4 + BodyLen);
Off := 1;
Frame[Off] := AnsiChar(VEC_BIN_MAGIC); Inc(Off);
Move(NSLen, Frame[Off], 2); Inc(Off, 2);
if NSLen > 0 then begin Move(NS[1], Frame[Off], NSLen); Inc(Off, NSLen); end;
Frame[Off] := AnsiChar(Cmd); Inc(Off);
Move(LblLen, Frame[Off], 2); Inc(Off, 2);
if LblLen > 0 then begin Move(ALabel[1], Frame[Off], LblLen); Inc(Off, LblLen); end;
Move(BodyLen, Frame[Off], 4); Inc(Off, 4);
if BodyLen > 0 then Move(Body[1], Frame[Off], BodyLen);
SendRaw(@Frame[1], Length(Frame));
end;
function TVecClient.RecvResponse: AnsiString;
var
Hdr: array[0..4] of Byte;
Status: Byte;
BodyLen: Cardinal;
Body: AnsiString;
begin
RecvExact(@Hdr[0], 5);
Status := Hdr[0];
Move(Hdr[1], BodyLen, 4);
Body := '';
if BodyLen > 0 then begin
SetLength(Body, BodyLen);
RecvExact(@Body[1], BodyLen);
end;
if Status = VEC_RESP_ERR then
raise Exception.Create(string(Body));
if Status <> VEC_RESP_OK then
raise Exception.CreateFmt('unknown status byte 0x%02x', [Status]);
Result := Body;
end;
function TVecClient.ParseRecords(const Body: AnsiString; Shape: Byte; Dim: Integer;
WithDistance: Boolean): TVecRecords;
var
Count: Cardinal;
Off: Integer;
I: Integer;
Idx: Integer;
Dist: Single;
LL, DL: Cardinal;
LbBuf: AnsiString;
DBuf: TByteArray;
V: TSingleArray;
begin
if Length(Body) < 4 then begin SetLength(Result, 0); Exit; end;
Move(Body[1], Count, 4);
SetLength(Result, Count);
Off := 5; { 1-based + 4 byte count prefix }
for I := 0 to Integer(Count) - 1 do begin
Move(Body[Off], Idx, 4); Inc(Off, 4);
Result[I].Index := Idx;
Dist := 0;
if WithDistance then begin
Move(Body[Off], Dist, 4); Inc(Off, 4);
end;
Result[I].Distance := Dist;
Result[I].Label_ := '';
SetLength(Result[I].Data, 0);
SetLength(Result[I].Vector, 0);
if (Shape and VEC_SHAPE_LABEL) <> 0 then begin
Move(Body[Off], LL, 4); Inc(Off, 4);
if LL > 0 then begin
SetLength(LbBuf, LL);
Move(Body[Off], LbBuf[1], LL);
Inc(Off, LL);
Result[I].Label_ := string(LbBuf);
end;
end;
if (Shape and VEC_SHAPE_DATA) <> 0 then begin
Move(Body[Off], DL, 4); Inc(Off, 4);
if DL > 0 then begin
SetLength(DBuf, DL);
Move(Body[Off], DBuf[0], DL);
Inc(Off, Integer(DL));
Result[I].Data := DBuf;
end;
end;
if (Shape and VEC_SHAPE_VECTOR) <> 0 then begin
SetLength(V, Dim);
Move(Body[Off], V[0], Dim * SizeOf(Single));
Inc(Off, Dim * SizeOf(Single));
Result[I].Vector := V;
end;
end;
end;
function TVecClient.EnsureDim: Integer;
var I: TVecInfo;
begin
if FDimCache > 0 then Exit(FDimCache);
I := Info;
FDimCache := I.Dim;
Result := FDimCache;
end;
{ ---------------- PUSH ---------------- }
function TVecClient.Push(const Vec: TSingleArray): Integer;
var Body: AnsiString; Zero: Cardinal; VBytes: Integer;
begin
VBytes := Length(Vec) * SizeOf(Single);
SetLength(Body, VBytes + 4);
if VBytes > 0 then Move(Vec[0], Body[1], VBytes);
Zero := 0;
Move(Zero, Body[VBytes + 1], 4);
SendFrame(VEC_CMD_PUSH, '', Body);
Body := RecvResponse;
Move(Body[1], Result, 4);
end;
function TVecClient.PushLabeled(const ALabel: string; const Vec: TSingleArray): Integer;
var Body: AnsiString; Zero: Cardinal; VBytes: Integer;
begin
VBytes := Length(Vec) * SizeOf(Single);
SetLength(Body, VBytes + 4);
if VBytes > 0 then Move(Vec[0], Body[1], VBytes);
Zero := 0;
Move(Zero, Body[VBytes + 1], 4);
SendFrame(VEC_CMD_PUSH, AnsiString(ALabel), Body);
Body := RecvResponse;
Move(Body[1], Result, 4);
end;
function TVecClient.PushFull(const ALabel: string; const Vec: TSingleArray; const Data: TByteArray): Integer;
var Body, R: AnsiString; DLen: Cardinal; VBytes: Integer;
begin
if (Length(Data) > 0) and (ALabel = '') then
raise Exception.Create('data requires label');
if Length(Data) > VEC_MAX_DATA_BYTES then
raise Exception.CreateFmt('data too large (%d > %d)', [Length(Data), VEC_MAX_DATA_BYTES]);
VBytes := Length(Vec) * SizeOf(Single);
DLen := Length(Data);
SetLength(Body, VBytes + 4 + Integer(DLen));
if VBytes > 0 then Move(Vec[0], Body[1], VBytes);
Move(DLen, Body[VBytes + 1], 4);
if DLen > 0 then Move(Data[0], Body[VBytes + 5], DLen);
SendFrame(VEC_CMD_PUSH, AnsiString(ALabel), Body);
R := RecvResponse;
Move(R[1], Result, 4);
end;
{ ---------------- QUERY ---------------- }
function TVecClient.Query(const Vec: TSingleArray): TVecRecords;
begin
Result := Query(Vec, False, VEC_SHAPE_FULL);
end;
function TVecClient.Query(const Vec: TSingleArray; Cosine: Boolean; Shape: Byte): TVecRecords;
var Body, R: AnsiString; VBytes: Integer; Dim: Integer;
begin
Dim := EnsureDim;
VBytes := Length(Vec) * SizeOf(Single);
SetLength(Body, 2 + VBytes);
if Cosine then Body[1] := AnsiChar(VEC_METRIC_COSINE) else Body[1] := AnsiChar(VEC_METRIC_L2);
Body[2] := AnsiChar(Shape);
if VBytes > 0 then Move(Vec[0], Body[3], VBytes);
SendFrame(VEC_CMD_QUERY, '', Body);
R := RecvResponse;
Result := ParseRecords(R, Shape, Dim, True);
end;
{ ---------------- QID ---------------- }
function TVecClient.QID(Index: Integer): TVecRecords;
begin
Result := QID(Index, False, VEC_SHAPE_FULL);
end;
function TVecClient.QID(Index: Integer; Cosine: Boolean; Shape: Byte): TVecRecords;
var Body, R: AnsiString; Dim: Integer;
begin
Dim := EnsureDim;
SetLength(Body, 6);
if Cosine then Body[1] := AnsiChar(VEC_METRIC_COSINE) else Body[1] := AnsiChar(VEC_METRIC_L2);
Body[2] := AnsiChar(Shape);
Move(Index, Body[3], 4);
SendFrame(VEC_CMD_QID, '', Body);
R := RecvResponse;
Result := ParseRecords(R, Shape, Dim, True);
end;
function TVecClient.QIDByLabel(const ALabel: string): TVecRecords;
begin
Result := QIDByLabel(ALabel, False, VEC_SHAPE_FULL);
end;
function TVecClient.QIDByLabel(const ALabel: string; Cosine: Boolean; Shape: Byte): TVecRecords;
var Body, R: AnsiString; Dim: Integer;
begin
Dim := EnsureDim;
SetLength(Body, 2);
if Cosine then Body[1] := AnsiChar(VEC_METRIC_COSINE) else Body[1] := AnsiChar(VEC_METRIC_L2);
Body[2] := AnsiChar(Shape);
SendFrame(VEC_CMD_QID, AnsiString(ALabel), Body);
R := RecvResponse;
Result := ParseRecords(R, Shape, Dim, True);
end;
{ ---------------- GET ---------------- }
function TVecClient.Get(Index: Integer; Shape: Byte): TVecRecords;
var Body, R: AnsiString; Dim: Integer;
begin
Dim := EnsureDim;
SetLength(Body, 6);
Body[1] := AnsiChar(VEC_GET_MODE_SINGLE);
Body[2] := AnsiChar(Shape);
Move(Index, Body[3], 4);
SendFrame(VEC_CMD_GET, '', Body);
R := RecvResponse;
Result := ParseRecords(R, Shape, Dim, False);
end;
function TVecClient.GetByLabel(const ALabel: string; Shape: Byte): TVecRecords;
var Body, R: AnsiString; Dim: Integer;
begin
Dim := EnsureDim;
SetLength(Body, 2);
Body[1] := AnsiChar(VEC_GET_MODE_SINGLE);
Body[2] := AnsiChar(Shape);
SendFrame(VEC_CMD_GET, AnsiString(ALabel), Body);
R := RecvResponse;
Result := ParseRecords(R, Shape, Dim, False);
end;
function TVecClient.GetBatch(const Indices: array of Integer; Shape: Byte): TVecRecords;
var Body, R: AnsiString; Dim, N, I: Integer; Cnt: Cardinal;
begin
Dim := EnsureDim;
N := Length(Indices);
Cnt := N;
SetLength(Body, 2 + 4 + N * 4);
Body[1] := AnsiChar(VEC_GET_MODE_BATCH);
Body[2] := AnsiChar(Shape);
Move(Cnt, Body[3], 4);
for I := 0 to N - 1 do
Move(Indices[I], Body[7 + I * 4], 4);
SendFrame(VEC_CMD_GET, '', Body);
R := RecvResponse;
Result := ParseRecords(R, Shape, Dim, False);
end;
{ ---------------- EXISTS ---------------- }
function TVecClient.Exists(const Vec: TSingleArray; Shape: Byte): TVecExistsResult;
var Body, R: AnsiString; VBytes: Integer; LL, DL: Cardinal; P: Integer;
begin
Result.Found := False;
Result.Index := -1;
Result.Label_ := '';
Result.Data := nil;
VBytes := Length(Vec) * SizeOf(Single);
SetLength(Body, 1 + VBytes);
Body[1] := AnsiChar(Shape);
if VBytes > 0 then Move(Vec[0], Body[2], VBytes);
SendFrame(VEC_CMD_EXISTS, '', Body);
R := RecvResponse;
if Length(R) < 1 then raise Exception.Create('EXISTS: empty response');
if Byte(R[1]) = 0 then Exit;
if Length(R) < 5 then raise Exception.Create('EXISTS: truncated response');
Result.Found := True;
Move(R[2], Result.Index, 4);
P := 6; { 1-based, after found(1) + index(4) }
if (Shape and VEC_SHAPE_LABEL) <> 0 then
begin
if Length(R) < P + 3 then raise Exception.Create('EXISTS: truncated label length');
Move(R[P], LL, 4); Inc(P, 4);
if LL > 0 then
begin
Result.Label_ := string(Copy(R, P, LL));
Inc(P, LL);
end;
end;
if (Shape and VEC_SHAPE_DATA) <> 0 then
begin
if Length(R) < P + 3 then raise Exception.Create('EXISTS: truncated data length');
Move(R[P], DL, 4); Inc(P, 4);
if DL > 0 then
begin
SetLength(Result.Data, DL);
Move(R[P], Result.Data[0], DL);
Inc(P, DL);
end;
end;
end;
{ ---------------- SET_DATA / GET_DATA ---------------- }
procedure TVecClient.SetData(Index: Integer; const Data: TByteArray);
var Body: AnsiString; DLen: Cardinal;
begin
if Length(Data) > VEC_MAX_DATA_BYTES then
raise Exception.CreateFmt('data too large (%d > %d)', [Length(Data), VEC_MAX_DATA_BYTES]);
DLen := Length(Data);
SetLength(Body, 8 + Integer(DLen));
Move(Index, Body[1], 4);
Move(DLen, Body[5], 4);
if DLen > 0 then Move(Data[0], Body[9], DLen);
SendFrame(VEC_CMD_SET_DATA, '', Body);
RecvResponse;
end;
procedure TVecClient.SetData(const ALabel: string; const Data: TByteArray);
var Body: AnsiString; DLen: Cardinal;
begin
if Length(Data) > VEC_MAX_DATA_BYTES then
raise Exception.CreateFmt('data too large (%d > %d)', [Length(Data), VEC_MAX_DATA_BYTES]);
DLen := Length(Data);
SetLength(Body, 4 + Integer(DLen));
Move(DLen, Body[1], 4);
if DLen > 0 then Move(Data[0], Body[5], DLen);
SendFrame(VEC_CMD_SET_DATA, AnsiString(ALabel), Body);
RecvResponse;
end;
function TVecClient.GetData(Index: Integer): TByteArray;
var Body, R: AnsiString; DLen: Cardinal;
begin
SetLength(Body, 4);
Move(Index, Body[1], 4);
SendFrame(VEC_CMD_GET_DATA, '', Body);
R := RecvResponse;
Move(R[1], DLen, 4);
SetLength(Result, DLen);
if DLen > 0 then Move(R[5], Result[0], DLen);
end;
function TVecClient.GetData(const ALabel: string): TByteArray;
var R: AnsiString; DLen: Cardinal;
begin
SendFrame(VEC_CMD_GET_DATA, AnsiString(ALabel), '');
R := RecvResponse;
Move(R[1], DLen, 4);
SetLength(Result, DLen);
if DLen > 0 then Move(R[5], Result[0], DLen);
end;
{ ---------------- UPDATE / LABEL / DELETE / UNDO ---------------- }
procedure TVecClient.Update(Index: Integer; const Vec: TSingleArray);
var Body: AnsiString; VBytes: Integer;
begin
VBytes := Length(Vec) * SizeOf(Single);
SetLength(Body, 4 + VBytes);
Move(Index, Body[1], 4);
if VBytes > 0 then Move(Vec[0], Body[5], VBytes);
SendFrame(VEC_CMD_UPDATE, '', Body);
RecvResponse;
end;
procedure TVecClient.UpdateByLabel(const ALabel: string; const Vec: TSingleArray);
var Body: AnsiString; VBytes: Integer;
begin
VBytes := Length(Vec) * SizeOf(Single);
SetLength(Body, VBytes);
if VBytes > 0 then Move(Vec[0], Body[1], VBytes);
SendFrame(VEC_CMD_UPDATE, AnsiString(ALabel), Body);
RecvResponse;
end;
procedure TVecClient.SetLabel(Index: Integer; const ALabel: string);
var Body: AnsiString;
begin
SetLength(Body, 4);
Move(Index, Body[1], 4);
SendFrame(VEC_CMD_LABEL, AnsiString(ALabel), Body);
RecvResponse;
end;
procedure TVecClient.Delete(Index: Integer);
var Body: AnsiString;
begin
SetLength(Body, 4);
Move(Index, Body[1], 4);
SendFrame(VEC_CMD_DELETE, '', Body);
RecvResponse;
end;
procedure TVecClient.Delete(const ALabel: string);
begin
SendFrame(VEC_CMD_DELETE, AnsiString(ALabel), '');
RecvResponse;
end;
procedure TVecClient.Undo;
begin
SendFrame(VEC_CMD_UNDO, '', '');
RecvResponse;
end;
procedure TVecClient.Save(out SavedCount: Cardinal; out CRC: Cardinal);
var R: AnsiString;
begin
SendFrame(VEC_CMD_SAVE, '', '');
R := RecvResponse;
Move(R[1], SavedCount, 4);
Move(R[5], CRC, 4);
end;
procedure TVecClient.Save;
var Saved, CRC: Cardinal;
begin
Save(Saved, CRC);
end;
function TVecClient.Info: TVecInfo;
var R: AnsiString; Off: Integer; NameLen: Cardinal; NameBuf: AnsiString;
begin
SendFrame(VEC_CMD_INFO, '', '');
R := RecvResponse;
Off := 1;
Move(R[Off], Result.Dim, 4); Inc(Off, 4);
Move(R[Off], Result.Count, 4); Inc(Off, 4);
Move(R[Off], Result.Deleted, 4); Inc(Off, 4);
Result.Fmt := Byte(R[Off]); Inc(Off);
Move(R[Off], Result.MTime, 8); Inc(Off, 8);
Move(R[Off], Result.CRC, 4); Inc(Off, 4);
Result.CRC_OK := Byte(R[Off]); Inc(Off);
Move(R[Off], NameLen, 4); Inc(Off, 4);
if NameLen > 0 then begin
SetLength(NameBuf, NameLen);
Move(R[Off], NameBuf[1], NameLen);
Result.Name := string(NameBuf);
Inc(Off, NameLen);
end else
Result.Name := '';
Result.ProtocolVersion := Byte(R[Off]);
end;
{ CLUSTER is binary; DISTINCT / REPRESENT carry text inside the binary envelope. }
{ DBSCAN clustering. The centroid of each cluster is the arithmetic mean of
its member vectors (fp32 even for f16 DBs). Use it to spot degenerate-
attractor clusters: a centroid with suspiciously small magnitude, or members
with high pairwise distance, often holds low-confidence/fallback embeddings
rather than a real coherent group. }
function TVecClient.Cluster(Eps: Single; Cosine: Boolean; MinPts: Integer): TVecClusterResult;
var
Body, R: AnsiString;
Mode: Byte;
Dim: Integer;
CCount, MCount, NCount: Cardinal;
Off: Integer;
C, I: Integer;
begin
Dim := EnsureDim;
SetLength(Body, 9);
Move(Eps, Body[1], 4);
if Cosine then Mode := VEC_METRIC_COSINE else Mode := VEC_METRIC_L2;
Body[5] := AnsiChar(Mode);
Move(MinPts, Body[6], 4);
SendFrame(VEC_CMD_CLUSTER, '', Body);
R := RecvResponse;
Off := 1; { 1-based AnsiString indexing }
Move(R[Off], CCount, 4); Inc(Off, 4);
SetLength(Result.Clusters, CCount);
for C := 0 to Integer(CCount) - 1 do begin
Move(R[Off], MCount, 4); Inc(Off, 4);
SetLength(Result.Clusters[C].Members, MCount);
for I := 0 to Integer(MCount) - 1 do begin
Move(R[Off], Result.Clusters[C].Members[I], 4);
Inc(Off, 4);
end;
SetLength(Result.Clusters[C].Centroid, Dim);
if Dim > 0 then begin
Move(R[Off], Result.Clusters[C].Centroid[0], Dim * SizeOf(Single));
Inc(Off, Dim * SizeOf(Single));
end;
end;
Move(R[Off], NCount, 4); Inc(Off, 4);
SetLength(Result.Noise, NCount);
for I := 0 to Integer(NCount) - 1 do begin
Move(R[Off], Result.Noise[I], 4);
Inc(Off, 4);
end;
end;
function TVecClient.DistinctRaw(K: Integer; Cosine: Boolean): TArray<string>;
var Body, R: AnsiString; Mode: Byte; Lines: TArray<string>; SS: TArray<string>; I: Integer;
begin
SetLength(Body, 5);
Move(K, Body[1], 4);
if Cosine then Mode := VEC_METRIC_COSINE else Mode := VEC_METRIC_L2;
Body[5] := AnsiChar(Mode);
SendFrame(VEC_CMD_DISTINCT, '', Body);
R := RecvResponse;
SS := string(R).Split([#10]);
SetLength(Lines, 0);
for I := 0 to Length(SS) - 1 do begin
if (SS[I] = '') or (SS[I] = 'end') then Continue;
SetLength(Lines, Length(Lines) + 1);
Lines[High(Lines)] := SS[I];
end;
Result := Lines;
end;
function TVecClient.RepresentRaw(Eps: Single; Cosine: Boolean; MinPts: Integer): TArray<string>;
var Body, R: AnsiString; Mode: Byte; Lines: TArray<string>; SS: TArray<string>; I: Integer;
begin
SetLength(Body, 9);
Move(Eps, Body[1], 4);
if Cosine then Mode := VEC_METRIC_COSINE else Mode := VEC_METRIC_L2;
Body[5] := AnsiChar(Mode);
Move(MinPts, Body[6], 4);
SendFrame(VEC_CMD_REPRESENT, '', Body);
R := RecvResponse;
SS := string(R).Split([#10]);
SetLength(Lines, 0);
for I := 0 to Length(SS) - 1 do begin
if (SS[I] = '') or (SS[I] = 'end') then Continue;
SetLength(Lines, Length(Lines) + 1);
Lines[High(Lines)] := SS[I];
end;
Result := Lines;
end;
procedure TVecClient.Close;
begin
if FPipeHandle <> INVALID_HANDLE_VALUE then begin
FlushFileBuffers(FPipeHandle);
CloseHandle(FPipeHandle);
FPipeHandle := INVALID_HANDLE_VALUE;
end;
FConnected := False;
end;
destructor TVecClient.Destroy;
begin
Close;
inherited;
end;
end.