Skip to content

Commit c394d6c

Browse files
committed
Overall improvements; refactoring
1 parent 680c84a commit c394d6c

File tree

7 files changed

+288
-302
lines changed

7 files changed

+288
-302
lines changed

SmartImage/Core/Interface.cs

Lines changed: 14 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -86,11 +86,7 @@ private static NConsoleOption[] AllOptions
8686
/// Utility color
8787
/// </summary>
8888
internal static readonly Color ColorUtility = Color.DarkOrange;
89-
90-
/// <summary>
91-
/// Misc color
92-
/// </summary>
93-
internal static readonly Color ColorMisc = Color.MediumPurple;
89+
9490

9591
/// <summary>
9692
/// Version color
@@ -125,9 +121,9 @@ private static NConsoleOption[] AllOptions
125121

126122
string? img = NConsole.ReadInput("Image", ColorMain);
127123

128-
img = img.CleanString();
124+
img = img?.CleanString();
129125

130-
if (!SearchClient.IsInputImageValid(img)) {
126+
if (!Images.IsInputImageValid(img)) {
131127

132128
NConsole.WriteError($"Invalid image!");
133129
NConsole.WaitForSecond();
@@ -136,7 +132,7 @@ private static NConsoleOption[] AllOptions
136132
}
137133

138134

139-
SearchConfig.Config.Image = img;
135+
SearchConfig.Config.ImageInput = img;
140136

141137
return true;
142138
}
@@ -263,7 +259,7 @@ private static string GetAutoFilterString()
263259
private static readonly NConsoleOption ShowInfoOption = new()
264260
{
265261
Name = "Show info and config",
266-
Color = ColorMisc,
262+
Color = ColorConfig,
267263
Function = () =>
268264
{
269265
Info.ShowInfo();
@@ -368,64 +364,28 @@ private static string GetContextMenuString(bool added) =>
368364
#if DEBUG
369365
private static readonly string[] TestImages =
370366
{
371-
"Test1.jpg",
372-
"Test2.jpg",
373-
"Test3.png"
367+
@"..\..\..\..\Test1.jpg",
368+
@"..\..\..\..\Test2.jpg",
369+
@"..\..\..\..\Test3.png",
370+
"https://kemono.party/files/224580/46935364/beidou_800.jpg"
374371
};
375372

376373
private static readonly NConsoleOption DebugTestOption = new()
377374
{
378375
Name = "[DEBUG] Run test",
379376
Function = () =>
380377
{
378+
379+
var rgOption = NConsoleOption.FromArray(TestImages, s => s);
380+
381+
string? testImg = (string) NConsole.ReadOptions(rgOption).First();
381382

382-
//var cd = new DirectoryInfo(Environment.CurrentDirectory);
383-
//var cd2 = cd.Parent.Parent.Parent.Parent.ToString();
384-
//var cd2 = cd.GetParentLevel(4).ToString();
385-
386-
string? cd2 = FileSystem.GetRelativeParent(Environment.CurrentDirectory, 4);
387-
388-
var rgOption = NConsoleOption.FromArray(TestImages, s => s);
389-
390-
string? testImg = (string) NConsole.ReadOptions(rgOption).First();
391-
392-
string? img = Path.Combine(cd2, testImg);
393-
394-
SearchConfig.Config.Image = img;
383+
SearchConfig.Config.ImageInput = testImg;
395384
//SearchConfig.Config.PriorityEngines = SearchEngineOptions.None;
396385

397386
return true;
398387
}
399388
};
400-
401-
/*private static readonly NConsoleOption DebugTestOption2 = new()
402-
{
403-
Name = "[DEBUG] Run test",
404-
Function = () =>
405-
{
406-
407-
var hashAlgorithm = new AverageHash();
408-
// or one of the other available algorithms:
409-
// var hashAlgorithm = new DifferenceHash();
410-
// var hashAlgorithm = new PerceptualHash();
411-
412-
string filename = NConsole.ReadInput("img1");
413-
using var stream = File.OpenRead(filename);
414-
415-
ulong imageHash = hashAlgorithm.Hash(stream);
416-
417-
418-
string filename2 = NConsole.ReadInput("img2");
419-
using var stream2 = Network.GetStreamFromUrl(filename2);
420-
421-
ulong imageHash2 = hashAlgorithm.Hash(stream2);
422-
423-
double percentageImageSimilarity = CompareHash.Similarity(imageHash, imageHash2);
424-
NConsole.WriteInfo($"{percentageImageSimilarity}");
425-
NConsole.WaitForSecond();
426-
return null;
427-
}
428-
};*/
429389
#endif
430390
}
431391
}

SmartImage/Core/SearchConfig.cs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -92,11 +92,13 @@ private SearchConfig()
9292

9393

9494
/// <summary>
95-
/// Image
95+
/// Image input (image file or URL)
9696
/// </summary>
97-
public string Image { get; set; }
97+
public string ImageInput { get; set; }
9898

99-
public bool HasImage => !string.IsNullOrWhiteSpace(Image);
99+
public bool HasImageInput => !string.IsNullOrWhiteSpace(ImageInput);
100+
101+
public bool UseImgur => !string.IsNullOrWhiteSpace(ImgurAuth);
100102

101103
/// <summary>
102104
/// Location of config file
@@ -128,7 +130,7 @@ private void ReadFromFile()
128130
}
129131

130132
// Should be initialized eventually
131-
Image = String.Empty;
133+
ImageInput = String.Empty;
132134
}
133135

134136
/// <summary>
@@ -172,10 +174,10 @@ public override string ToString()
172174
var sb = new StringBuilder();
173175

174176

175-
if (HasImage) {
177+
if (HasImageInput) {
176178
// Image may be null if not specified (error) or viewed in other UIs
177179
// if so, omit it
178-
var fi = new FileInfo(Image).Name;
180+
var fi = new FileInfo(ImageInput).Name;
179181
sb.AppendLabelWithColor(ColorPrimary, "Image", ColorMain, fi).AppendLine().AppendLine();
180182
}
181183

@@ -249,7 +251,7 @@ private void ReadFromArguments()
249251
break;
250252

251253
default:
252-
Image = parameterName;
254+
ImageInput = parameterName;
253255
break;
254256
}
255257
}

SmartImage/Engines/Other/YandexEngine.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,11 @@ public override FullSearchResult GetResult(string url)
113113

114114
var images = GetImages(doc);
115115

116+
if (!images.Any()) {
117+
sr.Filter = true;
118+
return sr;
119+
}
120+
116121
Debug.WriteLine($"{Name} has {images.Count} results");
117122
ISearchResult[] bestImages = FullSearchResult.FilterAndSelectBestImages(images);
118123

SmartImage/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ private static void Main(string[] args)
9696

9797

9898
// Exit if no image is given
99-
if (!SearchConfig.Config.HasImage) {
99+
if (!SearchConfig.Config.HasImageInput) {
100100
return;
101101
}
102102

SmartImage/Searching/FullSearchResult.cs

Lines changed: 103 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ namespace SmartImage.Searching
2727
/// </summary>
2828
/// <seealso cref="ISearchResult"/>
2929
/// <seealso cref="BasicSearchResult"/>
30-
public sealed class FullSearchResult : NConsoleOption, ISearchResult
30+
public sealed class FullSearchResult : NConsoleOption, ISearchResult, IComparable<FullSearchResult>
3131
{
3232
private const string ORIGINAL_IMAGE_NAME = "(Original image)";
3333

@@ -250,6 +250,30 @@ public void AddExtendedResults(ISearchResult[] bestImages)
250250
ExtendedResults.AddRange(CreateExtendedResults(bestImages));
251251
}
252252

253+
public int CompareTo(FullSearchResult? y)
254+
{
255+
float xSim = Similarity ?? 0;
256+
float ySim = y?.Similarity ?? 0;
257+
258+
if (xSim > ySim) {
259+
return -1;
260+
}
261+
262+
if (xSim < ySim) {
263+
return 1;
264+
}
265+
266+
if (ExtendedResults.Count > y?.ExtendedResults.Count) {
267+
return -1;
268+
}
269+
270+
if (Metadata.Count > y?.Metadata.Count) {
271+
return -1;
272+
}
273+
274+
return 0;
275+
}
276+
253277
public override string ToString()
254278
{
255279
var sb = new StringBuilder();
@@ -317,7 +341,7 @@ private void AppendResultInfo(StringBuilder sb, string name, string? value, bool
317341

318342
string? valueStr = value.AddColor(newColor);
319343
sb.Append($"\t{Formatting.ANSI_RESET}{name}: {valueStr}{Formatting.ANSI_RESET}\n");
320-
344+
321345
}
322346
}
323347

@@ -373,79 +397,85 @@ private IEnumerable<FullSearchResult> CreateExtendedResults(IReadOnlyList<ISearc
373397
return rg;
374398
}
375399

376-
public static int CompareResults(FullSearchResult x, FullSearchResult y)
400+
401+
private const float MAX_SIMILARITY = 100.0f;
402+
403+
private void AddImageInfo(ImageInputInfo info)
377404
{
378-
float xSim = x?.Similarity ?? 0;
379-
float ySim = y?.Similarity ?? 0;
405+
//todo
380406

381-
if (xSim > ySim) {
382-
return -1;
383-
}
407+
Bitmap bmp;
408+
string name;
409+
FileFormatType fileFormat;
410+
double bytes;
384411

385-
if (xSim < ySim) {
386-
return 1;
387-
}
412+
if (info.IsUrl) {
413+
name = info.Value.ToString();
388414

389-
if (x?.ExtendedResults.Count > y?.ExtendedResults.Count) {
390-
return -1;
391-
}
415+
using var netStream = Network.GetStreamFromUrl(info.ImageUrl);
416+
bmp = (Bitmap) Image.FromStream(netStream);
392417

393-
if (x?.Metadata.Count > y?.Metadata.Count) {
394-
return -1;
418+
netStream.Position = 0;
419+
using var ms = new MemoryStream();
420+
netStream.CopyTo(ms);
421+
var rg = ms.ToArray();
422+
fileFormat = FileSystem.ResolveFileType(rg);
423+
bytes = rg.Length;
395424
}
425+
else if (info.IsFile) {
426+
var imageFile = (FileInfo) info.Value;
396427

397-
return 0;
398-
}
428+
fileFormat = FileSystem.ResolveFileType(imageFile.FullName);
399429

400-
private void AddFileInfo(FileInfo imageFile)
401-
{
402-
403-
var fileFormat = FileSystem.ResolveFileType(imageFile.FullName);
430+
bmp = new Bitmap(imageFile.FullName);
431+
name = imageFile.Name;
432+
bytes = FileSystem.GetFileSize(imageFile.FullName);
433+
}
434+
else {
435+
throw new SmartImageException();
436+
}
404437

405-
double fileSizeMegabytes =
406-
MathHelper.ConvertToUnit(FileSystem.GetFileSize(imageFile.FullName), MetricUnit.Mega);
438+
string fileSize = MathHelper.ConvertToUnit(bytes);
407439

408-
(int width, int height) = Images.GetDimensions(imageFile.FullName);
440+
(int width, int height) = Images.GetDimensions(bmp);
409441

410442
Width = width;
411443
Height = height;
412444

413445
double mpx = MathHelper.ConvertToUnit(width * height, MetricUnit.Mega);
414446

415-
string? aspectRatio = new Fraction(width, height).ToString().Replace('/', ':');
416447

417-
string infoStr =
418-
$"{imageFile.Name} ({aspectRatio}) ({mpx:F} MP) ({fileSizeMegabytes:F} MB) ({fileFormat.Name})";
448+
var fraction = new Fraction(width, height);
449+
var fractionStr = fraction.ToString();
450+
451+
if (fractionStr == "1") {
452+
fractionStr = "1:1";
453+
}
454+
455+
string? aspectRatio = fractionStr.Replace('/', ':');
419456

457+
string fileInfoStr = $"{name} ({fileSize}) ({fileFormat.Name})";
458+
459+
string infoStr = $"({aspectRatio}) ({mpx:F} MP)";
460+
461+
Metadata.Add("File", fileInfoStr);
420462
Metadata.Add("Info", infoStr);
421463
}
422464

423-
private const float MAX_SIMILARITY = 100.0f;
424-
425465
/// <summary>
426466
/// Creates a <see cref="FullSearchResult" /> for the original image
427467
/// </summary>
428-
public static FullSearchResult GetOriginalImageResult(string imageUrl,
429-
[CanBeNull] FileInfo imageFile, [CanBeNull] string mimeType)
468+
public static FullSearchResult GetOriginalImageResult(ImageInputInfo info)
430469
{
431-
bool isFile = imageFile != null;
432-
string type = isFile ? "File" : "URI";
433-
434-
435-
var result = new FullSearchResult(Color.White, ORIGINAL_IMAGE_NAME + $" ({type})", imageUrl)
470+
var result = new FullSearchResult(Interface.ColorMisc2, ORIGINAL_IMAGE_NAME, info.ImageUrl)
436471
{
437472
IsOriginal = true,
438473
Similarity = MAX_SIMILARITY,
439474
IsAnalyzed = true
440-
};
441475

476+
};
442477

443-
if (mimeType != null) {
444-
result.Metadata.Add("Mime type", $"{mimeType}");
445-
}
446-
else if (isFile) {
447-
result.AddFileInfo(imageFile);
448-
}
478+
result.AddImageInfo(info);
449479

450480
return result;
451481
}
@@ -461,5 +491,34 @@ public static ISearchResult[] FilterAndSelectBestImages(List<BasicSearchResult>
461491

462492
return best;
463493
}
494+
495+
/// <summary>
496+
/// Handles result opening from priority engines and filtering
497+
/// </summary>
498+
public void HandlePriorityResult()
499+
{
500+
/*
501+
* Filtering is disabled
502+
* Open it anyway
503+
*/
504+
505+
if (!SearchConfig.Config.FilterResults) {
506+
Function();
507+
return;
508+
}
509+
510+
/*
511+
* Filtering is enabled
512+
* Determine if it passes the threshold
513+
*/
514+
515+
if (!Filter) {
516+
// Open result
517+
Function();
518+
}
519+
else {
520+
Debug.WriteLine($"Filtering result {Name}");
521+
}
522+
}
464523
}
465524
}

0 commit comments

Comments
 (0)