Skip to content

Commit e320328

Browse files
committed
Algorithm improvements
1 parent 2237824 commit e320328

File tree

7 files changed

+87
-104
lines changed

7 files changed

+87
-104
lines changed

SmartImage.Lib/Engines/Impl/YandexEngine.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Drawing;
55
using System.Linq;
66
using System.Text;
7+
using System.Text.Unicode;
78
using AngleSharp.Dom;
89
using AngleSharp.Html.Dom;
910
using AngleSharp.XPath;
@@ -216,8 +217,9 @@ protected override SearchResult Process(IDocument doc, SearchResult sr)
216217
if (looksLike != null) {
217218
//todo
218219

219-
sr.PrimaryResult.Description = Encoding.Unicode.GetString(
220-
Encoding.Convert(Encoding.UTF8, Encoding.Unicode, Encoding.UTF8.GetBytes(looksLike)));
220+
// sr.PrimaryResult.Description = Encoding.UTF8.GetString(
221+
// Encoding.Convert(Encoding.Unicode, Encoding.UTF8, Encoding.Unicode.GetBytes(looksLike)));
222+
sr.PrimaryResult.Description = looksLike;
221223
}
222224

223225
sr.OtherResults.AddRange(images);
@@ -232,5 +234,7 @@ protected override SearchResult Process(IDocument doc, SearchResult sr)
232234

233235
return sr;
234236
}
237+
238+
235239
}
236240
}

SmartImage.Lib/SearchClient.cs

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using SmartImage.Lib.Searching;
55
using SmartImage.Lib.Utilities;
66
using System;
7+
using System.Collections.Concurrent;
78
using System.Collections.Generic;
89
using System.ComponentModel;
910
using System.Diagnostics;
@@ -213,7 +214,7 @@ public List<SearchResult> MaximizeResults<T>(Func<SearchResult, T> property)
213214
public ImageResult[] FindDirectResults()
214215
{
215216

216-
var best = FindBestResults();
217+
var best = FindBestResults().ToList();
217218

218219
//const int FRAG_SIZE = 10;
219220

@@ -235,31 +236,51 @@ public ImageResult[] FindDirectResults()
235236

236237
//Task.WaitAll(tasks.ToArray());
237238

238-
var best1 = best;
239+
var bestCopy = best;
239240

240241
var options = new ParallelOptions()
241242
{
242243
MaxDegreeOfParallelism = Int32.MaxValue,
243244
TaskScheduler = TaskScheduler.Default,
244245
};
245246

246-
Parallel.For(0, best.Length, options, (i) =>
247+
Parallel.For(0, best.Count, options, (i) =>
247248
{
248-
best1[i].FindDirectImages();
249+
bestCopy[i].FindDirectImages();
249250

250251
});
251252

252-
best = best1;
253+
254+
best = bestCopy;
255+
256+
257+
bestCopy = best;
258+
259+
260+
var rx = new ConcurrentBag<ImageResult>();
261+
262+
Parallel.For(0, best.Count, options,(i) =>
263+
{
264+
if (ImageHelper.IsDirect(bestCopy[i].Direct?.ToString(), DirectImageType.Binary))
265+
{
266+
Debug.WriteLine($"Adding {bestCopy[i].Direct}");
267+
rx.Add(bestCopy[i]);
268+
}
269+
});
270+
271+
272+
best = rx.ToList();
253273

254274
best = best.Where(x => x.Direct != null)
255275
.OrderByDescending(r => r.Similarity)
256-
.ToArray();
276+
.ToList();
277+
278+
//best = best.OrderByDescending(b => b.PixelResolution).ToList();
257279

258280

259-
best = best.OrderByDescending(b => b.PixelResolution).ToArray();
260-
Debug.WriteLine($"Found {best.Length} direct results");
281+
Debug.WriteLine($"Found {best.Count} direct results");
261282

262-
return best;
283+
return best.ToArray();
263284
}
264285

265286
[CanBeNull]

SmartImage.Lib/Searching/ImageResult.cs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -125,13 +125,13 @@ public ImageResult()
125125
OtherMetadata = new Dictionary<string, object>();
126126
}
127127

128-
public static ImageResult FromDirectImage(DirectImage di)
128+
public static ImageResult FromDirectImage(string di)
129129
{
130130
var ir = new ImageResult
131131
{
132-
Image = di.Image,
133-
Url = (di.Direct),
134-
Direct = (di.Direct)
132+
Image = ImageHelper.GetImage(di),
133+
Url = new Uri((di)),
134+
Direct = new Uri((di))
135135
};
136136

137137
ir.UpdateImageData();
@@ -224,8 +224,7 @@ public void FindDirectImages()
224224
var direct = directImages?.FirstOrDefault();
225225

226226
if (direct != null) {
227-
Direct = (direct.Value.Direct);
228-
Image = direct.Value.Image;
227+
Direct = new Uri((direct));
229228
//Debug.WriteLine($"{Url} -> {Direct}");
230229

231230
}

SmartImage.Lib/Utilities/ImageHelper.cs

Lines changed: 21 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,11 @@
1818

1919
// ReSharper disable CognitiveComplexity
2020
// ReSharper disable PossibleNullReferenceException
21-
2221
// ReSharper disable UnusedParameter.Local
23-
2422
// ReSharper disable PossibleMultipleEnumeration
2523
// ReSharper disable AssignNullToNotNullAttribute
26-
2724
// ReSharper disable LoopCanBeConvertedToQuery
28-
2925
// ReSharper disable InconsistentNaming
30-
3126
// ReSharper disable UnusedMember.Global
3227

3328
namespace SmartImage.Lib.Utilities
@@ -150,22 +145,21 @@ public static Dictionary<string, string> UtilitiesMap
150145

151146
#endregion
152147

153-
154148
public static Image GetImage(string s)
155149
{
156-
// TODO: Using Image objects creates a memory leak; disposing them doesn't fix anything either (?)
157-
158150
using var wc = new WebClient();
159151

160-
byte[] buf = wc.DownloadData(s);
152+
//byte[] buf = wc.DownloadData(s);
161153

162-
var stream = new MemoryStream(buf);
154+
//using var stream = new MemoryStream(buf);
155+
//Debug.WriteLine($"Alloc {buf.Length}");
163156

164-
Debug.WriteLine($"Alloc {buf.Length}");
157+
using var stream = wc.OpenRead(s);
165158

166159
var image = Image.FromStream(stream);
167160

168161
return image;
162+
169163
}
170164

171165

@@ -176,13 +170,17 @@ public static Image GetImage(string s)
176170
/// <param name="directType">Which criterion to use to determine whether a URI is a direct image </param>
177171
/// <param name="count">Number of direct images to return</param>
178172
/// <param name="pingTimeSec"></param>
179-
/// <param name="readImage">Whether to read image metadata</param>
180-
/// <param name="imageFilter">Filter criteria for images (applicable iff <paramref name="readImage"/> is <c>true</c>)</param>
181-
public static List<DirectImage> FindDirectImages(string url, DirectImageType directType = DirectImageType.Regex,
182-
int count = 5, double pingTimeSec = 1, bool readImage = true,
183-
Predicate<Image> imageFilter = null)
173+
public static List<string> FindDirectImages(string url, DirectImageType directType = DirectImageType.Regex,
174+
int count = 5, double pingTimeSec = 1)
184175
{
185-
var images = new List<DirectImage>();
176+
/*
177+
* TODO
178+
*
179+
* This function creates an insane memory leak.
180+
* Disposing neither the images nor the streams does anything (?)
181+
*/
182+
183+
var images = new List<string>();
186184

187185
string gallerydl = UtilitiesMap[GALLERY_DL_EXE];
188186

@@ -206,21 +204,15 @@ public static List<DirectImage> FindDirectImages(string url, DirectImageType dir
206204

207205
var standardOutput = output.StandardOutput;
208206

207+
209208
while (!standardOutput.EndOfStream) {
210209
string str = standardOutput.ReadLine()
211210
.Split('|')
212211
.First();
212+
if (!string.IsNullOrWhiteSpace(str)) {
213+
images.Add(str);
213214

214-
var di = new DirectImage
215-
{
216-
Direct = new Uri(str),
217-
};
218-
219-
if (readImage) {
220-
di.Image = GetImage(str);
221215
}
222-
223-
images.Add(di);
224216
}
225217

226218
var standardError = output.StandardError;
@@ -239,8 +231,6 @@ public static List<DirectImage> FindDirectImages(string url, DirectImageType dir
239231

240232
manual:
241233

242-
imageFilter ??= (x) => true;
243-
244234
var pingTime = TimeSpan.FromSeconds(pingTimeSec);
245235

246236
IHtmlDocument document;
@@ -295,40 +285,13 @@ public static List<DirectImage> FindDirectImages(string url, DirectImageType dir
295285
if (!IsDirect(currentUrl, directType))
296286
return;
297287

298-
var di = new DirectImage
299-
{
300-
Direct = new Uri(currentUrl)
301-
};
302-
303-
304-
bool isValid = !readImage;
305-
306-
if (readImage) {
307-
try {
308-
var img = GetImage(currentUrl);
309-
310-
isValid = imageFilter(img);
311-
312-
if (isValid) {
313-
di.Image = img;
314-
315-
}
316-
else {
317-
img.Dispose();
318-
}
319-
}
320-
catch (Exception) {
321-
isValid = false;
322-
}
323-
}
324288

325289
if (imagesCopy.Count >= count) {
326290
return;
327291
}
328292

329-
if (isValid) {
330-
imagesCopy.Add(di);
331-
}
293+
imagesCopy.Add(currentUrl);
294+
332295
});
333296

334297

@@ -372,9 +335,6 @@ public static List<DirectImage> FindDirectImages(string url, DirectImageType dir
372335

373336
ret:
374337

375-
if (readImage) {
376-
images = images.OrderByDescending(x => x.Image.Width * x.Image.Height).ToList();
377-
}
378338

379339
return images;
380340

@@ -391,23 +351,7 @@ internal static string AsPercent(this float n)
391351
}
392352
}
393353

394-
public struct DirectImage : IDisposable
395-
{
396-
public Uri Direct { get; internal set; }
397-
398-
[CanBeNull]
399-
public Image Image { get; internal set; }
400-
401-
public override string ToString()
402-
{
403-
return $"{Direct} {Image?.Width}x{Image?.Height}";
404-
}
405-
406-
public void Dispose()
407-
{
408-
Image?.Dispose();
409-
}
410-
}
354+
411355

412356
public enum DirectImageType
413357
{

SmartImage/Core/AppInterface.cs

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using System.IO;
1010
using System.Linq;
1111
using System.Linq.Expressions;
12+
using System.Net;
1213
using System.Net.NetworkInformation;
1314
using System.Reflection;
1415
using System.Runtime.CompilerServices;
@@ -371,7 +372,8 @@ public static NConsoleOption[] CreateResultOptions(IEnumerable<ImageResult> resu
371372
return result.Select(r => CreateResultOption(r, $"{n} #{i++}", c)).ToArray();
372373
}
373374

374-
internal static NConsoleOption CreateResultOption(ImageResult result, string n, Color c, float correction=-.3f)
375+
internal static NConsoleOption CreateResultOption(ImageResult result, string n, Color c,
376+
float correction = -.3f)
375377
{
376378
var option = new NConsoleOption
377379
{
@@ -447,19 +449,25 @@ public static void ShowToast()
447449
var direct = Client.FindDirectResult();
448450

449451
Debug.WriteLine(direct);
450-
//Debug.WriteLine($"{Network.IsAlive(direct.Direct)} {ImageHelper.IsDirect(direct.Direct.ToString(), DirectImageType.Binary)}");
452+
Debug.WriteLine(direct.Direct.ToString());
451453

452454

455+
if (direct is {Direct: { }}) {
453456

454-
if (direct is { Direct: { } })
455-
{
456457

458+
var tmp = Path.GetTempPath();
457459

458-
string file = WebUtilities.Download(direct.Direct.ToString(), Path.GetTempPath());
460+
string filename = Path.GetFileName(direct.Direct.AbsolutePath);
459461

460-
Debug.WriteLine($"Downloaded {file} tmp");
461-
builder.AddHeroImage(new Uri(file));
462+
var file = Path.Combine(tmp, filename);
463+
464+
new WebClient().DownloadFile(direct.Direct, file);
462465

466+
//string file = WebUtilities.Download(abs.ToString(), s);
467+
468+
Debug.WriteLine($"Downloaded {file}");
469+
470+
builder.AddHeroImage(new Uri(file));
463471

464472
AppDomain.CurrentDomain.ProcessExit += (sender, args) =>
465473
{

0 commit comments

Comments
 (0)