-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathSearchCommand.cs
762 lines (562 loc) · 16.4 KB
/
SearchCommand.cs
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
// Read S SmartImage.Rdx SearchCommand.cs
// 2023-07-05 @ 2:07 AM
global using R2 = SmartImage.Rdx.Resources;
global using R1 = SmartImage.Lib.Resources;
// global using AC = Spectre.Console.AnsiConsole;
// global using AnsiConsole = Spectre.Console.AnsiConsole;
global using MN = System.Diagnostics.CodeAnalysis.MaybeNullAttribute;
global using CBN = JetBrains.Annotations.CanBeNullAttribute;
global using INN = JetBrains.Annotations.ItemNotNullAttribute;
global using NN = System.Diagnostics.CodeAnalysis.NotNullAttribute;
global using MNNW = System.Diagnostics.CodeAnalysis.MemberNotNullWhenAttribute;
global using MURV = JetBrains.Annotations.MustUseReturnValueAttribute;
using SmartImage.Lib;
using Spectre.Console;
using Spectre.Console.Cli;
using Kantan.Net.Utilities;
using SmartImage.Lib.Results;
using SmartImage.Lib.Utilities;
using Spectre.Console.Rendering;
using System.Collections.Concurrent;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Text;
using Flurl;
using JetBrains.Annotations;
using Kantan.Diagnostics;
using Kantan.Model.MemberIndex;
using Kantan.Utilities;
using Microsoft;
using Novus.Streams;
using Novus.Utilities;
using SixLabors.ImageSharp.Processing;
using CliWrap;
using Kantan.Text;
using SmartImage.Rdx.Shell;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Kantan.Monad;
using SmartImage.Lib.Engines;
using SmartImage.Lib.Engines.Impl.Search;
using SmartImage.Lib.Images;
using SmartImage.Lib.Images.Uni;
using SmartImage.Lib.Utilities.Diagnostics;
using SmartImage.Lib.Utilities.Integration;
// ReSharper disable InconsistentNaming
[assembly: InternalsVisibleTo("SmartImage.Lib.UnitTest")]
namespace SmartImage.Rdx.Commands;
#nullable disable
public sealed class SearchCommand : AsyncCommand<SearchCommandSettings>, IDisposable
{
public SearchClient Client { get; }
public SearchQuery Query { get; private set; }
public SearchConfig Config { get; }
private readonly CancellationTokenSource m_cts;
/// <summary>
/// Key: <see cref="SearchResult"/>
/// Value: <see cref="m_table"/> index
/// </summary>
private readonly ConcurrentDictionary<SearchResult, int> m_results;
private SearchCommandSettings m_scs;
private readonly STable m_table;
public SearchCommand()
{
Config = new SearchConfig();
// Config = (SearchConfig) cfg;
Client = new SearchClient(Config);
// Client.OnSearchComplete += OnSearchComplete;
// Client.OnResultComplete += OnResultComplete;
m_cts = new CancellationTokenSource();
m_scs = null;
m_table = CreateResultTable();
m_results = new();
Query = SearchQuery.Null;
}
#region
private async Task InitConfigAsync([CBN] object c)
{
//todo
Config.SearchEngines = m_scs.SearchEngines;
Config.PriorityEngines = m_scs.PriorityEngines;
Config.ReadCookies = m_scs.ReadCookies;
Config.FlareSolverr = m_scs.FlareSolverr;
Config.FlareSolverrApiUrl = m_scs.FlareSolverrApiUrl;
await Client.LoadEnginesAsync();
}
private async Task<bool> InitQueryAsync(ProgressContext ctx)
{
var p = ctx.AddTask("Creating query");
p.IsIndeterminate = true;
bool ok = true;
Query = await SearchQuery.TryCreateAsync(m_scs.Query);
if (Query == SearchQuery.Null) {
// throw new SmartImageException($"Could not create query"); //todo
ok = false;
goto ret;
}
p.Increment(ConsoleFormat.COMPLETE / 2);
// ctx.Refresh();
p.Description = "Uploading query";
var url = await Query.UploadAsync();
if (url == null) {
// throw new SmartImageException("Could not upload query"); //todo
ok = false;
goto ret;
}
p.Increment(ConsoleFormat.COMPLETE / 2);
ret:
return ok;
}
public override async Task<int> ExecuteAsync(CommandContext context, SearchCommandSettings settings)
{
m_scs = settings;
var task = AnsiConsole.Progress()
.AutoRefresh(true)
.StartAsync(InitQueryAsync);
try {
var ok = await task;
if (ok) {
var ci = ConsoleFormat.GetQueryCanvasImage(Query.Source);
var panel = new Panel(ci)
{
Header = new PanelHeader($"{Query.Source.ValueString}")
};
AnsiConsole.Write(panel);
await InitConfigAsync(ok);
}
else {
throw new SmartImageException("Could not upload query");
}
}
catch (Exception e) {
AnsiConsole.WriteException(e);
return BaseOSIntegration.EC_ERROR;
}
var gr = ConsoleFormat.CreateConfigGrid(Config, Query);
AnsiConsole.Write(gr);
Console.CancelKeyPress += OnCancelKeyPress;
/*
*
* todo
*/
Task run;
#if !UNITTEST
run = AnsiConsole.Live(m_table)
.StartAsync(RunSearchLiveAsync);
#else
run = RunSearchLiveAsync(null);
#endif
if (!string.IsNullOrWhiteSpace(m_scs.Command)) {
run = run.ContinueWith(RunCompletionCommandAsync, m_cts.Token,
TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
}
if (!string.IsNullOrWhiteSpace(m_scs.OutputFile)) {
switch (m_scs.OutputFileFormat) {
case OutputFileFormat.None:
break;
case OutputFileFormat.Delimited:
run = run.ContinueWith(WriteOutputFile, m_cts.Token,
TaskContinuationOptions.OnlyOnRanToCompletion,
TaskScheduler.Default);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
await run;
Task run2;
if (m_scs.Interactive) {
run2 = RunInteractiveAsync();
// run2 = ShowImageScanResultsAsync(item);
await run2;
}
if (m_scs.KeepOpen) {
while (!AnsiConsole.Confirm("Exit")) {
// ...
}
}
return BaseOSIntegration.EC_OK;
}
private async Task RunInteractiveAsync()
{
string cmd = null;
do {
cmd = GetCommandPrompt();
if (cmd != R2.Chc_Exit) {
var sr = GetEnginePrompt();
var num = GetNumberPrompt(sr);
var res = sr.Results[num];
if (cmd == R2.Chc_Open) {
SearchClient.OpenResult(res.Url);
}
else if (cmd == R2.Chc_Scan) {
var run3 = ShowImageScanResultsAsync(res);
await run3;
var cmd2 = GetCommand2Prompt();
if (cmd2 == "back") {
goto cont;
}
else if (cmd2 == "calculate") {
await AnsiConsole.Live(m_table).StartAsync(async (f) =>
{
var ui = res.Uni[0];
var hashOk = ui.TryCalculateSimilarity(Query.Source);
if (hashOk) {
var row = GetRow(ui);
m_table.Rows.Update(row, 2, new Text(res.Similarity.ToString()));
f.Refresh();
}
});
// var row = dict[item];
// table2.Rows.Update(row, 2, new Text(item.Similarity.ToString()));
}
}
}
else { }
cont:
continue;
} while (cmd != R2.Chc_Exit);
}
// TODO: Rewrite RunSearch counterparts
private async Task RunSearchLiveAsync(LiveDisplayContext c)
{
#if UNITTEST
return;
#endif
var search = Client.RunSearchAsync(Query, token: m_cts.Token);
while (await Client.ResultChannel.Reader.WaitToReadAsync()) {
var result = await Client.ResultChannel.Reader.ReadAsync();
m_results.TryAdd(result, BaseOSIntegration.EC_ERROR);
// m_results.Add(result);
/*var txt = new Text(result.Engine.Name, GetEngineColor(result.Engine.EngineOption));
var txt2 = new Text($"{result.Results.Count}");
m_mainTable.AddRow(txt, txt2);*/
var rows = CreateResultRows(result);
m_results[result] = m_table.Rows.Count;
foreach (IRenderable[] row in rows) {
m_table.AddRow(row);
}
c.Refresh();
}
await search;
}
private async ValueTask ShowImageScanResultsAsync(SearchResultItem item)
{
/*var gr2 = new Grid();
gr2.AddColumns(5);
gr2.AddRow(CreateResultItemRows(item, 0, Style.Plain));
// AnsiConsole.Write(gr2);
var tr = new Tree(gr2);
var ld = AnsiConsole.Live(tr);*/
// var table2 = CreateResultTable();
// table2.AddRow(CreateResultItemRows(item, 0, Style.Plain));
// var ld = AnsiConsole.Live(table2);
await AnsiConsole.Live(m_table).StartAsync(async (f) =>
{
if (!item.HasUni) {
// var ok = await r.ScanAsync();
Trace.WriteLine($"Scanning {item}");
var resOk = await item.ScanAsync();
if (!resOk) {
Debugger.Break();
}
}
int i = 0;
var row = GetRow(item);
var rowOrig = row;
var delta = item.Uni.Length;
var idx = item.Root.Results.IndexOf(item);
foreach (var ui in item.Uni) {
m_table.InsertRow(++row, CreateUniImageRow(ui, item, idx, i++));
}
foreach (var kv in m_results) {
if (kv.Value >= rowOrig) {
m_results[kv.Key] = kv.Value + delta;
}
}
});
}
private async Task RunCompletionCommandAsync([CBN] object o)
{
Debug.WriteLine($"{nameof(RunCompletionCommandAsync)}");
var command = Cli.Wrap(m_scs.Command);
var cmdArgs = m_scs.CommandArguments;
var stdOutBuffer = new StringBuilder();
var stdErrBuffer = new StringBuilder();
if (!string.IsNullOrWhiteSpace(cmdArgs)) {
command = command.WithArguments(cmdArgs);
}
command = command.WithStandardErrorPipe(PipeTarget.ToStringBuilder(stdErrBuffer))
.WithStandardOutputPipe(PipeTarget.ToStringBuilder(stdOutBuffer));
var commandTask = command.ExecuteAsync(m_cts.Token);
AnsiConsole.WriteLine($"Process id: {commandTask.ProcessId}");
var result = await commandTask;
AnsiConsole.WriteLine($"Process successful: {result.IsSuccess}");
}
private void WriteOutputFile([CBN] object o)
{
Debug.WriteLine($"{nameof(WriteOutputFile)}");
var fw = File.OpenWrite(m_scs.OutputFile);
var sw = new StreamWriter(fw)
{
AutoFlush = true
};
var fields = m_scs.OutputFields;
bool fName = fields.HasFlag(OutputFields.Name);
var fUrl = fields.HasFlag(OutputFields.Url);
var fSim = fields.HasFlag(OutputFields.Similarity);
var fArtist = fields.HasFlag(OutputFields.Artist);
var fSite = fields.HasFlag(OutputFields.Site);
var names = Enum.GetValues<OutputFields>()
.Where(f => fields.HasFlag(f) && !f.Equals(default(OutputFields)))
.Select(Enum.GetName);
sw.WriteLine(string.Join(m_scs.OutputFileDelimiter, names));
foreach (SearchResult sr in m_results.Keys) {
for (int j = 0; j < sr.Results.Count; j++) {
var sri = sr.Results[j];
var rg = new List<string>();
if (fName)
rg.Add($"{sr.Engine.Name} #{j + 1}");
if (fUrl)
rg.Add(sri.Url);
if (fSim)
rg.Add($"{sri.Similarity}");
if (fArtist)
rg.Add($"{sri.Artist}");
if (fSite)
rg.Add($"{sri.Site}");
// string[] items = [$"{sr.Engine.Name} #{j + 1}", sri.Url?.ToString()];
sw.WriteLine(string.Join(m_scs.OutputFileDelimiter, rg));
}
}
sw.Dispose();
fw.Dispose();
AnsiConsole.WriteLine($"Wrote to {m_scs.OutputFile}");
}
#endregion
private SearchResultItem GetItemForUni(UniImage ui, out int uniIndex)
{
foreach (SearchResult sr in m_results.Keys) {
foreach (var sri in sr.Results) {
if (sri.HasUni) {
for (int k = 0; k < sri.Uni.Length; k++) {
UniImage ui2 = sri.Uni[k];
if (ui == ui2) {
uniIndex = k;
return sri;
}
}
}
}
}
uniIndex = BaseOSIntegration.EC_ERROR;
return null;
}
private int GetRow(object o)
{
int a = 0, b = 0, c = 0;
SearchResultItem sri;
switch (o) {
case UniImage ui:
sri = GetItemForUni(ui, out c);
break;
case SearchResultItem sri2:
sri = sri2;
break;
default:
Debugger.Break();
return BaseOSIntegration.EC_ERROR;
// throw new SmartImageException($"{o} is invalid");
// return null;
}
a = m_results[sri.Root];
b = sri.Root.Results.IndexOf(sri);
return a + b + c;
}
#region Prompts
private static string GetCommand2Prompt()
{
var textPrompt = new TextPrompt<string>(Markup.Escape("[Command 2]"))
{
ShowChoices = true,
Choices =
{
"calculate", "back"
}
};
var prompt = AnsiConsole.Prompt(textPrompt);
return prompt;
}
private int GetNumberPrompt(SearchResult result)
{
Prm_Num.Validator = i =>
{
if (i < result.Results.Count && i >= 0) {
return ValidationResult.Success();
}
return ValidationResult.Error("Out of range");
};
return AnsiConsole.Prompt(Prm_Num);
}
private string GetCommandPrompt()
{
return AnsiConsole.Prompt(Prm_Command);
}
private SearchResult GetEnginePrompt()
{
if (Client.IsComplete && !Prm_Engine.Choices.Any()) {
Prm_Engine.Choices.AddRange(m_results.Keys);
}
return AnsiConsole.Prompt(Prm_Engine);
}
#endregion
#region
private static IRenderable[] CreateUniImageRow(UniImage ui, SearchResultItem sri, int idx, int subIdx)
{
// var url = ui is UniImageUri uiu ? uiu.Url.ToString() : String.Empty;
if (ui is UniImageUri uiu) {
Debug.Assert(uiu.Url == ui.ValueString);
}
var result = sri.Root;
var style = new Style(link: ui.ValueString,
foreground: ConsoleFormat.GetEngineColor(result.Engine.EngineOption));
return
[
new Text($"{result.Engine.Name} #{idx}.{subIdx}", style),
new Text(Markup.Escape(ui.ValueString)),
ConsoleFormat.Txt_Empty,
ConsoleFormat.Txt_Empty,
ConsoleFormat.Txt_Empty
];
}
private SearchResultItem ParseResultFromPrompt(string input)
{
var inputSplit = input.Split(' ', StringSplitOptions.TrimEntries);
var name = inputSplit[0];
var res = m_results.Keys.FirstOrDefault(
sr => sr.Engine.Name.Contains(name, StringComparison.InvariantCultureIgnoreCase));
if (res != default && inputSplit.Length > 1 && int.TryParse(inputSplit[1], out var idx)) {
var sri = res.Results[idx];
return sri;
}
return null;
}
private static STable CreateResultTable()
{
var col = new TableColumn[]
{
new("Result"),
new("URL"),
new("Similarity"),
new("Artist"),
new("Site"),
};
var tb = new STable()
{
Caption = new TableTitle("Results", new Style(decoration: Decoration.Bold)),
Border = TableBorder.Simple,
ShowHeaders = true,
};
tb.AddColumns(col);
return tb;
}
private static IEnumerable<IRenderable[]> CreateResultRows(SearchResult result)
{
Style style = ConsoleFormat.GetEngineColor(result.Engine.EngineOption);
var lr = style.Foreground.GetLuminance();
var lrr = style.Foreground.GetContrastRatio(Color.White);
var lrr2 = style.Foreground.GetContrastRatio(Color.Black);
// Debug.WriteLine($"{lr} {lrr} {lrr2}");
for (int i = 0; i < result.Results.Count; i++) {
var res = result.Results[i];
yield return CreateResultItemRows(res, i, style);
}
}
private static IRenderable[] CreateResultItemRows(SearchResultItem res, int i, Style style)
{
var name = new Text($"{res.Root.Engine.Name} #{i}", style);
IRenderable url;
var link = res.Url;
if (link != null) {
url = new Markup(Markup.Escape(link.ToString()), new Style(link: link));
}
else {
url = ConsoleFormat.Txt_NA;
}
var sim = new Text($"{res.Similarity}");
var artist = new Text($"{res.Artist}");
var site = new Text($"{res.Site}");
return [name, url, sim, artist, site];
}
private Layout CreateConfigLayout()
{
// Create the layout
var layout = new Layout("Root")
.SplitColumns(
new Layout("Left"),
new Layout("Right"));
// Update the left column
layout["Right"].Update(
new Panel(Align.Center(new Text("---"))).Expand());
return layout;
}
#endregion
[ContractAnnotation("=> halt")]
private void OnCancelKeyPress(object sender, ConsoleCancelEventArgs args)
{
AnsiConsole.MarkupLine($"[red]Cancellation requested[/]");
AnsiConsole.Clear();
m_cts.Cancel();
args.Cancel = false;
Environment.Exit(BaseOSIntegration.EC_ERROR);
}
public override ValidationResult Validate(CommandContext context, SearchCommandSettings settings)
{
var r = base.Validate(context, settings);
return r;
}
public void Dispose()
{
Debug.WriteLine($"Disposing {nameof(SearchCommand)}");
foreach (var sr in m_results.Keys) {
sr.Dispose();
}
Prm_Num.Validator = null;
Prm_Engine.Choices.Clear();
m_results.Clear();
m_cts.Dispose();
m_scs = null;
Client.Dispose();
Query.Dispose();
}
#region Prompts
private static readonly TextPrompt<string> Prm_Command = new(Markup.Escape("[Command]"))
{
ShowChoices = true,
ShowDefaultValue = true,
AllowEmpty = false,
Choices =
{
R2.Chc_Open, R2.Chc_Scan, R2.Chc_Exit
}
};
private static readonly TextPrompt<SearchResult> Prm_Engine = new(Markup.Escape("[Engine]"))
{
ShowChoices = false,
ShowDefaultValue = false,
AllowEmpty = false,
Converter = s =>
{
//
return s.Engine.Name;
}
};
private static readonly TextPrompt<int> Prm_Num = new(Markup.Escape("[#]"))
{
ShowChoices = false,
ShowDefaultValue = false,
AllowEmpty = false,
};
#endregion
}