Skip to content

Commit

Permalink
Rdx work; 1.0.3
Browse files Browse the repository at this point in the history
  • Loading branch information
Decimation committed Apr 25, 2024
1 parent 1e844a0 commit 9f08e08
Show file tree
Hide file tree
Showing 7 changed files with 133 additions and 68 deletions.
2 changes: 1 addition & 1 deletion SmartImage.Lib 3/Engines/Impl/Search/EHentaiEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ protected override async Task<IDocument> GetDocumentAsync(SearchResult sr, Searc
}
}
else {
var ok = query.LoadFile(name);
var ok = query.TryGetFile(name);

if (ok) {
t = query.FilePath;
Expand Down
45 changes: 17 additions & 28 deletions SmartImage.Lib 3/SearchQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ namespace SmartImage.Lib;
public enum QueryType
{

Unknown = 0,
File,
Uri,
Stream
Expand Down Expand Up @@ -71,23 +72,14 @@ public long Size
[MNNW(true, nameof(Upload))]
public bool IsUploaded => Url.IsValid(Upload);

public bool IsUploading { get; private set; }

[MNNW(true, nameof(Value))]
public bool HasValue => Value != null;

[MN]
public string FilePath { get; private set; }

[MNNW(true, nameof(FilePath))]
public bool HasFile => FilePath != null;

internal SearchQuery([MN] object f)
{
Value = f;

// Size = Uni == null ? default : Uni.Stream.Length;
}
public bool HasFile => FilePath != null && File.Exists(FilePath);

internal SearchQuery([MN] object f, Stream s, QueryType type)
{
Expand All @@ -98,6 +90,8 @@ internal SearchQuery([MN] object f, Stream s, QueryType type)
// Size = Uni == null ? default : Uni.Stream.Length;
}

internal SearchQuery([MN] object f) : this(f, Stream.Null, QueryType.Unknown) { }

private SearchQuery() : this(null) { }

static SearchQuery() { }
Expand Down Expand Up @@ -126,7 +120,6 @@ public static async Task<SearchQuery> TryCreateAsync(object o, CancellationToken
str = File.OpenRead(s);
qt = QueryType.File;
}

else if (IsUriType(o, out var url2)) {
var url = (Url) url2;
var res = await HandleUriAsync(url, t);
Expand All @@ -144,12 +137,12 @@ public static async Task<SearchQuery> TryCreateAsync(object o, CancellationToken
fmt = await ISImage.DetectFormatAsync(str, t);
str.TrySeek();

var sq2 = new SearchQuery(o, str, qt)
var query = new SearchQuery(o, str, qt)
{
ImageInfo = fmt
};

return sq2;
return query;
}

public static async Task<IFlurlResponse> HandleUriAsync(Url value, CancellationToken ct)
Expand Down Expand Up @@ -177,8 +170,6 @@ public async Task<Url> UploadAsync(BaseUploadEngine engine = null, CancellationT
return Upload;
}

IsUploading = true;

string fu = Value.ToString();

if (Type == QueryType.Uri) {
Expand Down Expand Up @@ -227,12 +218,10 @@ public async Task<Url> UploadAsync(BaseUploadEngine engine = null, CancellationT
u.Dispose();
}

IsUploading = false;

return Upload;
}

#region
#region

public static bool IsStreamType(object o, out Stream t2)
{
Expand Down Expand Up @@ -267,8 +256,6 @@ public static bool IsFileType(object o, out FileInfo f)
return f != null;
}

#endregion

public static bool IsValidSourceType(object str)
{
// UniSourceType v = UniHandler.GetUniType(str, out object o2);
Expand All @@ -285,6 +272,8 @@ public static bool IsValidSourceType(object str)
return ok;
}

#endregion

public void Dispose()
{
Stream?.Dispose();
Expand All @@ -295,7 +284,7 @@ public void Dispose()

public override string ToString()
{
string s = $"{Stream} | {ValueString}";
string s = $"{ValueString} ({Type}) [{ImageInfo.DefaultMimeType}]";

return s;
}
Expand Down Expand Up @@ -336,19 +325,19 @@ public override int GetHashCode()

#endregion

public bool LoadFile(string fn = null)
public bool TryGetFile(string fn = null)
{
if (!HasFile && HasValue) {
FilePath = GetFilePathOrTemp(fn);
FilePath = WriteToFile(fn);

}

return HasFile;
}

public bool DeleteFile()
public bool TryDeleteFile()
{
if (File.Exists(FilePath)) {
if (HasFile) {
File.Delete(FilePath);
FilePath = null;
}
Expand All @@ -357,7 +346,7 @@ public bool DeleteFile()
}

[MustUseReturnValue]
public string WriteToFile(Action<IImageProcessingContext> operation = null, [CanBeNull] string fn = null)
public string WriteToFile(Action<IImageProcessingContext> operation = null, [CBN] string fn = null)
{
if (!HasValue) {
throw new InvalidOperationException();
Expand All @@ -368,7 +357,7 @@ public string WriteToFile(Action<IImageProcessingContext> operation = null, [Can

var encoder = new PngEncoder();

using Image image = ISImage.Load(Stream);
using ISImage image = ISImage.Load(Stream);

if (operation != null) {
image.Mutate(operation);
Expand All @@ -384,7 +373,7 @@ public string WriteToFile(Action<IImageProcessingContext> operation = null, [Can

[MustUseReturnValue]
[ICBN]
public string GetFilePathOrTemp(string fn = null)
public string WriteToFile(string fn = null)
{
if (!HasValue) {
throw new InvalidOperationException($"{nameof(HasValue)} is {false}");
Expand Down
109 changes: 77 additions & 32 deletions SmartImage.Rdx/SearchCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
using Kantan.Text;
using SmartImage.Rdx.Shell;
using System.Linq;
using Kantan.Monad;

namespace SmartImage.Rdx;

Expand All @@ -57,7 +58,8 @@ internal sealed class SearchCommand : AsyncCommand<SearchCommandSettings>, IDisp

private SearchCommandSettings m_scs;

private const double COMPLETE = 100.0d;
private readonly STable m_table;
private const double COMPLETE = 100.0d;

public const int EC_ERROR = -1;
public const int EC_OK = 0;
Expand All @@ -75,8 +77,8 @@ public SearchCommand()
m_cts = new CancellationTokenSource();
m_results = new ConcurrentBag<SearchResult>();
m_scs = null;

Query = SearchQuery.Null;
m_table = CreateResultTable();
Query = SearchQuery.Null;
}

#region
Expand Down Expand Up @@ -118,39 +120,49 @@ private async Task InitConfigAsync([CBN] object c)

}

private async Task RunSearchAsync(ProgressContext c)
private async Task RunSearchLiveAsync(LiveDisplayContext c)
{

var search = Client.RunSearchAsync(Query, token: m_cts.Token, reload: false);

while (await Client.ResultChannel.Reader.WaitToReadAsync()) {
var result = await Client.ResultChannel.Reader.ReadAsync();

m_results.Add(result);

if (m_scs.LiveDisplay.HasValue && m_scs.LiveDisplay.Value) {
UpdateResultTable(result);
}

c.Refresh();
}

await search;

}

// TODO: Rewrite RunSearch counterparts

private async Task RunSearchWithProgressAsync(ProgressContext c)
{
var cnt = (double) Client.Engines.Length;
var pt = c.AddTask("Running search", maxValue: cnt);
pt.IsIndeterminate = true;

// var p2 = c.AddTask("Engines", maxValue: cnt);

// Client.OnResult += OnResultComplete;

var search = Client.RunSearchAsync(Query, token: m_cts.Token, reload: false);

while (await Client.ResultChannel.Reader.WaitToReadAsync()) {
var result = await Client.ResultChannel.Reader.ReadAsync();

m_results.Add(result);

pt.Description = $"{result.Engine.Name} {m_results.Count} / {cnt}";
pt.Increment(1);
c.Refresh();

if (m_scs.HideResultTable.HasValue && !m_scs.HideResultTable.Value) {
Table tb = CreateResultTable(result);
AConsole.Write(tb);

}
}

await search;

// Debug.WriteLine($"{nameof(RunSearchAsync)} complete");

return;

}

public override async Task<int> ExecuteAsync(CommandContext context, SearchCommandSettings settings)
Expand All @@ -171,11 +183,20 @@ public override async Task<int> ExecuteAsync(CommandContext context, SearchComma

/*
*
* todo
*/

var run = AConsole.Progress()
.AutoRefresh(false)
.StartAsync(RunSearchAsync);
Task run;

if (m_scs.LiveDisplay.HasValue && m_scs.LiveDisplay.Value) {
run = AConsole.Live(m_table)
.StartAsync(RunSearchLiveAsync);

}
else {
run = AConsole.Progress()
.StartAsync(RunSearchWithProgressAsync);
}

if (!String.IsNullOrWhiteSpace(m_scs.Command)) {
run = run.ContinueWith(RunCompletionCommandAsync, m_cts.Token,
Expand Down Expand Up @@ -320,33 +341,55 @@ private void OnCancelKeyPress(object sender, ConsoleCancelEventArgs args)

#endregion

private Table CreateResultTable(SearchResult result)
#region

private static STable CreateResultTable()
{
var col = new TableColumn[]
{
new("Result"),
new("URL"),
new("Similarity")
new("Similarity"),
new("Artist"),
new("Site"),

};

var tb = new Table()
var tb = new STable()
{
Caption = new TableTitle(result.Engine.Name),
Border = TableBorder.Simple,
Caption = new TableTitle("Results", new Style(decoration: Decoration.Bold)),
Border = TableBorder.Simple,
ShowHeaders = true,
};

tb.AddColumns(col);

return tb;
}

private void UpdateResultTable(SearchResult result)
{

if (!CliFormat.EngineStyles.TryGetValue(result.Engine.EngineOption, out var style)) {
style = Style.Plain;
}

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];
var name = new Text($"{result.Engine.Name} #{i}", CliFormat.EngineStyles[result.Engine.EngineOption]);
var url = new Text($"{res.Url}");
var sim = new Text($"{res.Similarity}");
tb.AddRow(name, url, sim);
var res = result.Results[i];
var name = new Text($"{result.Engine.Name} #{i}", style);
var url = new Markup($"[link]{res.Url}[/]");
var sim = new Text($"{res.Similarity}");
var artist = new Text($"{res.Artist}");
var site = new Text($"{res.Site}");
m_table.AddRow(name, url, sim, artist, site);
}

return tb;
}

private Grid CreateInfoGrid()
Expand All @@ -373,6 +416,8 @@ private Grid CreateInfoGrid()
return dt;
}

#endregion

public override ValidationResult Validate(CommandContext context, SearchCommandSettings settings)
{
var r = base.Validate(context, settings);
Expand Down
6 changes: 3 additions & 3 deletions SmartImage.Rdx/SearchCommandSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ internal sealed class SearchCommandSettings : CommandSettings
[Description("Read cookies from browser")]
public bool? ReadCookies { get; internal set; }

[CommandOption("--hide-table")]
[CommandOption("--live")]
[DefaultValue(false)]
[Description("Hide result table")]
public bool? HideResultTable { get; internal set; }
[Description("Live result display")]
public bool? LiveDisplay { get; internal set; }

#region

Expand Down
Loading

0 comments on commit 9f08e08

Please sign in to comment.