-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathuMainForm.pas
428 lines (365 loc) · 12.7 KB
/
uMainForm.pas
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
unit uMainForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.StorageBin, FMX.Memo.Types, FMX.Controls.Presentation,
FMX.ScrollBox, FMX.Memo, FMX.ListBox, FMX.StdCtrls, FMX.Layouts, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, System.Rtti,
System.Bindings.Outputs, Fmx.Bind.Editors, Data.Bind.EngExt,
Fmx.Bind.DBEngExt, Data.Bind.Components, Data.Bind.DBScope, REST.Types,
FMX.Edit, FMX.Effects, REST.Response.Adapter, REST.Client,
Data.Bind.ObjectScope, FMX.ListView.Types, FMX.ListView.Appearances,
FMX.ListView.Adapters.Base, FMX.EditBox, FMX.ComboTrackBar, FMX.ComboEdit,
FMX.ListView, FMX.TabControl, System.Threading,
FMX.MultiView, FMX.Grid.Style, Fmx.Bind.Grid,
Data.Bind.Controls, Fmx.Bind.Navigator, Data.Bind.Grid, FMX.Grid;
type
TMainForm = class(TForm)
Layout1: TLayout;
Layout2: TLayout;
InputMemo: TMemo;
PromptMemo: TMemo;
MaterialOxfordBlueSB: TStyleBook;
OutputMemo: TMemo;
BindSourceDB1: TBindSourceDB;
BindingsList1: TBindingsList;
ToolBar1: TToolBar;
ShadowEffect4: TShadowEffect;
Label1: TLabel;
APIKeyButton: TButton;
OAAPIKeyEdit: TEdit;
StatusBar1: TStatusBar;
ComposeButton: TButton;
RESTClient1: TRESTClient;
RESTRequest1: TRESTRequest;
RESTResponse1: TRESTResponse;
RESTResponseDataSetAdapter1: TRESTResponseDataSetAdapter;
FDMemTable1: TFDMemTable;
RequestVariationButton: TButton;
BindSourceDB2: TBindSourceDB;
LinkFillControlToField: TLinkFillControlToField;
BindSourceDB3: TBindSourceDB;
LinkFillControlToField1: TLinkFillControlToField;
BindSourceDB4: TBindSourceDB;
StatusLabel: TLabel;
BindSourceDB5: TBindSourceDB;
TabControl2: TTabControl;
TabItem4: TTabItem;
TabItem5: TTabItem;
HistoryGrid: TStringGrid;
HistoryMT: TFDMemTable;
BindSourceDB6: TBindSourceDB;
LinkGridToDataSourceBindSourceDB6: TLinkGridToDataSource;
BindNavigator1: TBindNavigator;
Layout8: TLayout;
ModelsMT: TFDMemTable;
BindSourceDB7: TBindSourceDB;
ProgressBar: TProgressBar;
Timer: TTimer;
Splitter1: TSplitter;
LoadRecordButton: TButton;
APIKeyEdit: TEdit;
RESTClient2: TRESTClient;
RESTResponse2: TRESTResponse;
RESTRequest2: TRESTRequest;
RESTResponseDataSetAdapter2: TRESTResponseDataSetAdapter;
FDMemTable2: TFDMemTable;
RESTClient3: TRESTClient;
RESTResponse3: TRESTResponse;
RESTRequest3: TRESTRequest;
RESTResponseDataSetAdapter3: TRESTResponseDataSetAdapter;
FDMemTable3: TFDMemTable;
PredictionMemo: TMemo;
VersionEdit: TComboBox;
LinkListControlToField1: TLinkListControlToField;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
LanguagesMT: TFDMemTable;
LanguageCB1: TComboBox;
LanguageCB2: TComboBox;
Label5: TLabel;
BindSourceDB8: TBindSourceDB;
LinkFillControlToField2: TLinkFillControlToField;
LinkFillControlToField3: TLinkFillControlToField;
Layout3: TLayout;
LoadButton: TButton;
OpenDialog: TOpenDialog;
procedure APIKeyButtonClick(Sender: TObject);
procedure ComposeButtonClick(Sender: TObject);
procedure TimerTimer(Sender: TObject);
procedure RequestVariationButtonClick(Sender: TObject);
procedure OutputMemoChange(Sender: TObject);
procedure LoadRecordButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure HistoryGridResize(Sender: TObject);
procedure LoadButtonClick(Sender: TObject);
private
{ Private declarations }
function CreateOpenAIChatJSON(const AModel, APrompt: string; AMaxTokens: Integer): string;
function CreateReplicateJSON(const AVersion, APrompt: string): string;
public
{ Public declarations }
FVariation: Boolean;
end;
var
MainForm: TMainForm;
implementation
{$R *.fmx}
uses
System.JSON, System.IOUtils, StrUtils;
function TMainForm.CreateOpenAIChatJSON(const AModel, APrompt: string; AMaxTokens: Integer): string;
var
RootObj, SystemMessageObj, UserMessageObj: TJSONObject;
MessagesArray: TJSONArray;
begin
RootObj := TJSONObject.Create;
try
RootObj.AddPair('model', AModel);
MessagesArray := TJSONArray.Create;
try
SystemMessageObj := TJSONObject.Create;
SystemMessageObj.AddPair('role', 'system');
SystemMessageObj.AddPair('content', 'You are the best written and spoken language expert in the world and know how to translate text between all languages.');
MessagesArray.AddElement(SystemMessageObj);
//if OutPutMemo.Lines.Text='' then
begin
UserMessageObj := TJSONObject.Create;
UserMessageObj.AddPair('role', 'user');
UserMessageObj.AddPair('content', APrompt);
MessagesArray.AddElement(UserMessageObj);
end;
if FVariation=True then
begin
if OutPutMemo.Lines.Text<>'' then
begin
UserMessageObj := TJSONObject.Create;
UserMessageObj.AddPair('role', 'assistant');
UserMessageObj.AddPair('content', OutPutMemo.Lines.Text);
MessagesArray.AddElement(UserMessageObj);
end;
if OutPutMemo.Lines.Text<>'' then
begin
UserMessageObj := TJSONObject.Create;
UserMessageObj.AddPair('role', 'user');
UserMessageObj.AddPair('content', 'Take another look and refine the translation. Fix any mistakes.');
MessagesArray.AddElement(UserMessageObj);
end;
end;
RootObj.AddPair('messages', MessagesArray);
except
MessagesArray.Free;
raise;
end;
// RootObj.AddPair('max_tokens', TJSONNumber.Create(AMaxTokens));
Result := RootObj.Format(2); // The number 2 is to specify the formatting indent size
finally
RootObj.Free;
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
var LFilePath := TPath.Combine(TPath.GetDocumentsPath,'aitranslate.fds');
if TFile.Exists(LFilePath) then
begin
HistoryMT.LoadFromFile(LFilepath);
HistoryGridResize(Sender);
end;
LanguageCB1.ItemIndex := 0;
LanguageCB2.ItemIndex := 22;
end;
procedure TMainForm.HistoryGridResize(Sender: TObject);
begin
if HistoryGrid.ColumnCount>0 then
for var I := 0 to HistoryGrid.ColumnCount-1 do
begin
HistoryGrid.Columns[I].Width := Trunc(Trunc(HistoryGrid.Width) / HistoryGrid.ColumnCount);
end;
end;
procedure TMainForm.LoadButtonClick(Sender: TObject);
begin
if OpenDialog.Execute then
InputMemo.Lines.LoadFromFile(OpenDialog.Filename);
end;
procedure TMainForm.LoadRecordButtonClick(Sender: TObject);
begin
PromptMemo.Lines.Text := HistoryMT.FieldByName('PromptText').AsWideString;
InputMemo.Lines.Text := HistoryMT.FieldByName('InputText').AsWideString;
OutputMemo.Lines.Text := HistoryMT.FieldByName('OutputText').AsWideString;
end;
procedure TMainForm.OutputMemoChange(Sender: TObject);
begin
if OutputMemo.Lines.Text<>'' then
RequestVariationButton.Enabled := True
else
RequestVariationButton.Enabled := False;
end;
procedure TMainForm.RequestVariationButtonClick(Sender: TObject);
begin
FVariation := True;
RequestVariationButton.Enabled := False;
ComposeButtonClick(Sender);
end;
procedure TMainForm.APIKeyButtonClick(Sender: TObject);
begin
APIKeyEdit.Visible := not APIKeyEdit.Visible;
OAAPIKeyEdit.Visible := not OAAPIKeyEdit.Visible;
end;
function GetMessageContent(const JSONArray: string): string;
var
JSONData: TJSONArray;
MessageObj: TJSONObject;
begin
Result := '';
JSONData := TJSONObject.ParseJSONValue(JSONArray) as TJSONArray;
try
MessageObj := (JSONData.Items[0] as TJSONObject).GetValue<TJSONObject>('message');
Result := MessageObj.GetValue<string>('content');
finally
JSONData.Free;
end;
end;
procedure TMainForm.TimerTimer(Sender: TObject);
begin
if ProgressBar.Visible = False then
begin
Timer.Enabled := False;
end
else
begin
if ProgressBar.Value=ProgressBar.Max then
ProgressBar.Value := ProgressBar.Min
else
ProgressBar.Value := ProgressBar.Value+5;
end;
end;
function ConcatJSONStrings(const JSONArray: string): string;
var
JSONData: TJSONArray;
I: Integer;
begin
if JSONArray[1]='[' then
begin
Result := '';
JSONData := TJSONObject.ParseJSONValue(JSONArray) as TJSONArray;
try
for I := 0 to JSONData.Count - 1 do
Result := Result + JSONData.Items[I].Value;
finally
JSONData.Free;
end;
end
else
Result := JSONArray;
end;
function TMainForm.CreateReplicateJSON(const AVersion, APrompt: string): string;
var
RootObj, InputObj: TJSONObject;
begin
RootObj := TJSONObject.Create;
try
RootObj.AddPair('version', AVersion);
InputObj := TJSONObject.Create;
try
var LPrompt := '';
if FVariation=True then
begin
LPrompt := APrompt + ' Here is a translation: ' + OutPutMemo.Lines.Text + ' Take another look at the above text and refine the translation.';
end
else
begin
LPrompt := APrompt;
end;
InputObj.AddPair('prompt', LPrompt);
// InputObj.AddPair('max_tokens', TJSONNumber.Create(AMaxTokens));
RootObj.AddPair('input', InputObj);
except
InputObj.Free;
raise;
end;
Result := RootObj.ToString;
finally
RootObj.Free;
end;
end;
procedure TMainForm.ComposeButtonClick(Sender: TObject);
begin
if ((OAAPIKeyEdit.Text='') and (ModelsMT.FieldByName('provider').AsWideString='openai')) then
begin
ShowMessage('Enter an OpenAI.com API key.');
Exit;
end;
if ((APIKeyEdit.Text='') and (ModelsMT.FieldByName('provider').AsWideString='replicate')) then
begin
ShowMessage('Enter a Replicate.com API key.');
Exit;
end;
ComposeButton.Enabled := False;
ProgressBar.Visible := True;
Timer.Enabled := True;
TTask.Run(procedure begin
if ModelsMT.FieldByName('provider').AsWideString='openai' then
begin
RESTRequest1.Params[0].Value := 'Bearer ' + OAAPIKeyEdit.Text;
RESTRequest1.Params[1].Value := CreateOpenAIChatJSON(VersionEdit.Selected.Text, PromptMemo.Lines.Text.Replace('%input%',LanguageCB1.Selected.Text).Replace('%output%',LanguageCB2.Selected.Text) + ' ' + InputMemo.Lines.Text, 2000);
RESTRequest1.Execute;
if FDMemTable1.FindField('choices')<>nil then
begin
TThread.Synchronize(nil,procedure begin
OutputMemo.Lines.Text := GetMessageContent(FDMemTable1.FieldByName('choices').AsWideString);
StatusLabel.Text := FDMemTable1.FieldByName('usage').AsWideString;
RequestVariationButton.Enabled := True;
HistoryMT.AppendRecord([PromptMemo.Lines.Text, InputMemo.Lines.Text, OutputMemo.Lines.Text]);
HistoryMT.SaveToFile(TPath.Combine(TPath.GetDocumentsPath,'aitranslate.fds'));
end);
end;
end
else if ModelsMT.FieldByName('provider').AsWideString='replicate' then
begin
RESTRequest2.Params[0].Value := 'Token ' + APIKeyEdit.Text;
RESTRequest2.Params[1].Value := CreateReplicateJSON(ModelsMT.FieldByName('model').AsWideString, PromptMemo.Lines.Text.Replace('%input%',LanguageCB1.Selected.Text).Replace('%output%',LanguageCB2.Selected.Text) + ' "' + InputMemo.Lines.Text + '"');
RESTRequest2.Execute;
if FDMemTable2.FindField('id')<>nil then
begin
var LStatus := 'started';
while ((LStatus<>'succeeded') AND (LStatus<>'failed')) do
begin
RESTRequest3.Resource := FDMemTable2.FieldByName('id').AsWideString;
RESTRequest3.Params[0].Value := 'Token ' + APIKeyEdit.Text;
RESTRequest3.Execute;
LStatus := FDMemTable3.FieldByName('status').AsWideString;
if LStatus='succeeded' then
begin
var LOutput := ConcatJSONStrings(FDMemTable3.FieldByName('output').AsWideString);
if LOutput<>'' then
begin
TThread.Synchronize(nil,procedure begin
StatusLabel.Text := LStatus;
OutputMemo.Lines.Text := LOutput;
RequestVariationButton.Enabled := True;
HistoryMT.AppendRecord([PromptMemo.Lines.Text, InputMemo.Lines.Text, OutputMemo.Lines.Text]);
HistoryMT.SaveToFile(TPath.Combine(TPath.GetDocumentsPath,'aitranslate.fds'));
end);
end;
end
else
begin
TThread.Synchronize(nil,procedure begin
StatusLabel.Text := LStatus;
end);
end;
Sleep(3000);
end;
end;
end;
TThread.Synchronize(nil,procedure begin
ComposeButton.Enabled := True;
ProgressBar.Visible := False;
end);
FVariation := False;
end);
end;
end.