Skip to content

Commit e91bbd6

Browse files
committed
Experimenting
1 parent 4494f6d commit e91bbd6

File tree

7 files changed

+85
-69
lines changed

7 files changed

+85
-69
lines changed

SmartImage.Lib/SearchClient.cs

Lines changed: 28 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ public SearchClient(SearchConfig config)
5555
/// Contains search results
5656
/// </summary>
5757
public List<SearchResult> Results { get; }
58+
59+
5860

5961
/// <summary>
6062
/// Contains filtered search results
@@ -164,26 +166,34 @@ public async Task RunSearchAsync()
164166
var args = new SearchCompletedEventArgs
165167
{
166168
Results = Results,
167-
Detailed = new Lazy<ImageResult>(() => GetDetailedResults().FirstOrDefault()),
169+
Detailed = new Lazy<ImageResult>(() => GetDetailedImageResults().FirstOrDefault()),
168170
Direct = new Lazy<ImageResult[]>(() =>
169171
{
170172
Debug.WriteLine($"{nameof(SearchClient)}: Finding direct results", C_DEBUG);
171-
ImageResult[] direct = GetDirectResults();
173+
ImageResult[] direct = GetDirectImageResults();
172174

173175
return direct;
174176
}),
175-
FirstDirect = new Lazy<ImageResult>(GetDirectResult)
177+
FirstDirect = new Lazy<ImageResult>(GetDirectImageResult)
176178
};
177179

178180
SearchCompleted?.Invoke(null, args);
179181
}
180182

183+
184+
/*
185+
* TODO
186+
*
187+
* Queue a thread to run in the background upon each result completion
188+
* in which the thread scans for direct images, instead of doing the scanning post hoc
189+
*/
190+
181191
#endregion
182192

183193
#region Secondary operations
184194

185195
/// <summary>
186-
/// Refines search results by searching with the most-detailed result (<see cref="GetDirectResult" />).
196+
/// Refines search results by searching with the most-detailed result (<see cref="GetDirectImageResult" />).
187197
/// </summary>
188198
public async Task RefineSearchAsync()
189199
{
@@ -193,7 +203,7 @@ public async Task RefineSearchAsync()
193203

194204
Debug.WriteLine($"{nameof(SearchClient)}: Finding best result", C_DEBUG);
195205

196-
var directResult = GetDirectResult();
206+
var directResult = GetDirectImageResult();
197207

198208
if (directResult == null) {
199209
throw new SmartImageException("Could not find best result");
@@ -228,47 +238,32 @@ public List<SearchResult> MaximizeResults<T>(Func<SearchResult, T> property)
228238
}
229239

230240
[CanBeNull]
231-
public ImageResult GetDirectResult() => GetDirectResults(1)?.FirstOrDefault();
241+
public ImageResult GetDirectImageResult() => GetDirectImageResults(1)?.FirstOrDefault();
232242

233-
public ImageResult[] GetDirectResults(int count = 5)
243+
public ImageResult[] GetDirectImageResults(int count = 5)
234244
{
245+
var imageResults = RefineFilter(DirectFilterPredicate).ToList();
235246

236-
// var best = FindBestResults().ToList();
237-
/*var best = Results.Where(r => r.IsNonPrimitive)
238-
.Where(r => r.Engine.SearchType.HasFlag(EngineSearchType.Image))
239-
.AsParallel()
240-
.OrderByDescending(r => r.PrimaryResult.Similarity)
241-
.ThenByDescending(r => r.PrimaryResult.PixelResolution)
242-
.ThenByDescending(r => r.PrimaryResult.DetailScore)
243-
.SelectMany(r =>
244-
{
245-
var x = r.OtherResults;
246-
x.Insert(0, r.PrimaryResult);
247-
return x;
248-
})
249-
.ToList();*/
250-
251-
var results = RefineFilter(r => DetailPredicate(r)
252-
&& r.Engine.SearchType.HasFlag(EngineSearchType.Image)).ToList();
253-
254-
Debug.WriteLine($"{nameof(SearchClient)}: Found {results.Count} best results", C_DEBUG);
247+
Debug.WriteLine($"{nameof(SearchClient)}: Found {imageResults.Count} best results", C_DEBUG);
255248

256249
const int i = 10;
257250

258-
var query = results.Where(x => x.CheckDirect(DirectImageCriterion.Regex))
251+
var query = imageResults.Where(x => x.CheckDirect(DirectImageCriterion.Regex))
259252
.Take(i)
260253
.AsParallel();
261254

262255
List<ImageResult> images;
263256

264-
if (count == 1) {
257+
if (count == 1)
258+
{
265259
images = new List<ImageResult>
266260
{
267261
query.FirstOrDefault(x => x.CheckDirect(DirectImageCriterion.Binary))
268262
};
269263

270264
}
271-
else {
265+
else
266+
{
272267
images = query.Where(x => x.CheckDirect(DirectImageCriterion.Binary))
273268
.Take(count)
274269
// .OrderByDescending(r => r.Similarity)
@@ -284,7 +279,7 @@ public ImageResult[] GetDirectResults(int count = 5)
284279
/// Selects the most detailed results.
285280
/// </summary>
286281
/// <returns>The <see cref="ImageResult" />s of the best <see cref="Results" /></returns>
287-
public ImageResult[] GetDetailedResults() => RefineFilter(DetailPredicate).ToArray();
282+
public ImageResult[] GetDetailedImageResults() => RefineFilter(DetailPredicate).ToArray();
288283

289284
public IEnumerable<ImageResult> RefineFilter(Predicate<SearchResult> predicate)
290285
{
@@ -334,6 +329,9 @@ public static BaseSearchEngine[] GetAllSearchEngines()
334329
private static readonly Predicate<SearchResult> DetailPredicate = r => r.IsNonPrimitive;
335330

336331
private static readonly SmartImageException SearchException = new("Search must be completed");
332+
333+
private static readonly Predicate<SearchResult> DirectFilterPredicate = r => DetailPredicate(r)
334+
&& r.Engine.SearchType.HasFlag(EngineSearchType.Image);
337335
}
338336

339337
public sealed class SearchCompletedEventArgs : EventArgs

SmartImage.Lib/Searching/ImageResult.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Diagnostics;
34
using System.Diagnostics.CodeAnalysis;
45
using System.Drawing;
56
using System.Linq;
@@ -208,12 +209,14 @@ public async void FindDirectImages()
208209

209210
try {
210211

211-
var directImages = await ImageHelper.FindDirectImages(Url.ToString());
212+
var directImages = await ImageHelper.ScanForImages(Url.ToString());
212213

213214
var direct = directImages.FirstOrDefault();
214215

215216
if (direct != null) {
216217
Direct = new Uri((direct));
218+
219+
Debug.WriteLine($"Found direct images");
217220
}
218221
}
219222
catch {

SmartImage.Lib/Utilities/ImageHelper.cs

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,17 @@
33
using System.Diagnostics;
44
using System.Drawing;
55
using System.Drawing.Drawing2D;
6-
using System.Drawing.Imaging;
76
using System.IO;
87
using System.Linq;
98
using System.Net;
10-
using System.Net.Http;
119
using System.Text.RegularExpressions;
1210
using System.Threading;
1311
using System.Threading.Tasks;
1412
using System.Web;
1513
using AngleSharp.Html.Dom;
16-
using AngleSharp.Html.Parser;
1714
using JetBrains.Annotations;
18-
using Kantan.Collections;
19-
using Kantan.Diagnostics;
20-
using Novus.Win32;
2115
using Kantan.Net;
22-
using Kantan.Utilities;
16+
using Novus.Win32;
2317
using RestSharp;
2418
using static Kantan.Diagnostics.LogCategories;
2519

@@ -149,7 +143,7 @@ private static string NormalizeFilename(Uri src)
149143
/// <param name="url">Url to search</param>
150144
/// <param name="count">Number of direct images to return</param>
151145
/// <param name="timeoutMS"></param>
152-
public static async Task<List<string>> FindDirectImages(string url, int count = 10, long timeoutMS = TimeoutMS)
146+
public static async Task<List<string>> ScanForImages(string url, int count = 10, long timeoutMS = TimeoutMS)
153147
{
154148

155149
var images = new List<string>();
@@ -315,16 +309,16 @@ public static Bitmap ResizeImage(Bitmap mg, Size newSize)
315309
myThumbWidth = Math.Ceiling(mg.Width / ratio);
316310

317311
//Size thumbSize = new Size((int)myThumbWidth, (int)myThumbHeight);
318-
Size thumbSize = new Size((int) newSize.Width, (int) newSize.Height);
312+
var thumbSize = new Size(newSize.Width, newSize.Height);
319313
bp = new Bitmap(newSize.Width, newSize.Height);
320314
x = (newSize.Width - thumbSize.Width) / 2;
321315
y = (newSize.Height - thumbSize.Height);
322316
// Had to add System.Drawing class in front of Graphics ---
323-
System.Drawing.Graphics g = Graphics.FromImage(bp);
317+
Graphics g = Graphics.FromImage(bp);
324318
g.SmoothingMode = SmoothingMode.HighQuality;
325319
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
326320
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
327-
Rectangle rect = new Rectangle(x, y, thumbSize.Width, thumbSize.Height);
321+
var rect = new Rectangle(x, y, thumbSize.Width, thumbSize.Height);
328322
g.DrawImage(mg, rect, 0, 0, mg.Width, mg.Height, GraphicsUnit.Pixel);
329323

330324
return bp;

SmartImage/Core/AppInfo.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,15 @@ public static void Setup()
8989
throw new NotSupportedException();
9090
}*/
9191

92+
// Remove old path directories
93+
var pathDirectories = FileSystem.GetEnvironmentPathDirectories();
94+
var oldFolders = pathDirectories.Where(x=>x.Contains(NAME) && x!= AppFolder);
95+
96+
foreach (string s in oldFolders) {
97+
FileSystem.RemoveFromPath(s);
98+
}
99+
100+
92101
if (!IsAppFolderInPath) {
93102
AppIntegration.HandlePath(true);
94103
}

SmartImage/Program.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ public static class Program
142142

143143
#endregion
144144

145-
145+
146146
/// <summary>
147147
/// Entry point
148148
/// </summary>
@@ -153,13 +153,14 @@ private static async Task Main(string[] args)
153153
* Check compatibility
154154
* Register events
155155
*/
156+
156157

157158
ToastNotificationManagerCompat.OnActivated += AppToast.OnToastActivated;
158159

159160
Console.OutputEncoding = Encoding.Unicode;
160161

161162
Console.Title = $"{AppInfo.NAME}";
162-
163+
163164
//120,30
164165

165166
ConsoleManager.Init();

SmartImage/UI/AppToast.cs

Lines changed: 35 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using Kantan.Diagnostics;
44
using Kantan.Net;
55
using Kantan.Numeric;
6+
using Kantan.Text;
67
using Microsoft.Toolkit.Uwp.Notifications;
78
using SmartImage.Lib;
89
using SmartImage.Lib.Utilities;
@@ -14,6 +15,7 @@ internal static class AppToast
1415
internal static void ShowToast(object sender, SearchCompletedEventArgs args)
1516
{
1617
Debug.WriteLine($"Building toast", LogCategories.C_DEBUG);
18+
1719
var bestResult = args.Detailed;
1820

1921
var builder = new ToastContentBuilder();
@@ -34,6 +36,8 @@ internal static void ShowToast(object sender, SearchCompletedEventArgs args)
3436

3537
if (Program.Config.Notification && Program.Config.NotificationImage) {
3638

39+
Debug.Assert(args.FirstDirect != null);
40+
3741
var imageResult = args.FirstDirect.Value;
3842

3943
if (imageResult != null) {
@@ -44,6 +48,8 @@ internal static void ShowToast(object sender, SearchCompletedEventArgs args)
4448
if (file == null) {
4549
int i = 0;
4650

51+
Debug.Assert(args.Direct != null);
52+
4753
var imageResults = args.Direct.Value;
4854

4955
do {
@@ -54,14 +60,14 @@ internal static void ShowToast(object sender, SearchCompletedEventArgs args)
5460
}
5561

5662
if (file != null) {
57-
58-
file = GetHeroImage(path, file);
63+
// NOTE: The file size limit doesn't seem to actually matter ...
64+
//file = GetHeroImage(path, file);
5965

6066
Debug.WriteLine($"{nameof(AppInterface)}: Downloaded {file}", LogCategories.C_INFO);
6167

6268
builder.AddHeroImage(new Uri(file));
6369

64-
AppDomain.CurrentDomain.ProcessExit += (sender2, args2) =>
70+
AppDomain.CurrentDomain.ProcessExit += (_, _) =>
6571
{
6672
File.Delete(file);
6773
};
@@ -73,38 +79,43 @@ internal static void ShowToast(object sender, SearchCompletedEventArgs args)
7379
}
7480

7581
builder.SetBackgroundActivation();
76-
77-
//...
78-
7982
builder.Show();
80-
81-
// ToastNotificationManager.CreateToastNotifier();
8283
}
8384

84-
private static string GetHeroImage(string path, string file)
85+
private static string GetHeroImage(string folder, string filePath)
8586
{
86-
var bytes = File.ReadAllBytes(file).Length;
87-
var kiloBytes = MathHelper.ConvertToUnit(bytes, MetricPrefix.Kilo);
87+
// NOTE: The file size limit doesn't seem to actually matter ...
88+
89+
/*var bytes = File.ReadAllBytes(filePath).Length;
90+
var kiloBytes = MathHelper.ConvertToUnit(bytes, MetricPrefix.Kilo);
91+
92+
8893
bool tooBig = kiloBytes >= MAX_IMG_SIZE_KB;
8994
9095
if (tooBig) {
91-
var bitmap = new Bitmap(file);
92-
var newSize = new Size(Convert.ToInt32(bitmap.Width / 2), Convert.ToInt32(bitmap.Height / 2));
93-
Bitmap bitmap2 = ImageHelper.ResizeImage(bitmap, newSize);
94-
95-
if (bitmap2 != null) {
96-
string s = Path.Combine(path, Path.GetTempFileName());
97-
bitmap2.Save(s, System.Drawing.Imaging.ImageFormat.Jpeg);
98-
bytes = File.ReadAllBytes(file).Length;
96+
var bitmap = new Bitmap(filePath);
97+
var newSize = new Size(Convert.ToInt32(bitmap.Width / 2), Convert.ToInt32(bitmap.Height / 2));
98+
Bitmap newBitmap = ImageHelper.ResizeImage(bitmap, newSize);
99+
100+
if (newBitmap != null) {
101+
var fileWithoutExt = Path.GetFileNameWithoutExtension(filePath);
102+
var ext = Path.GetExtension(filePath);
103+
104+
string newFile = Path.Combine(folder, fileWithoutExt + "-1" + ext);
105+
106+
newBitmap.Save(newFile, System.Drawing.Imaging.ImageFormat.Jpeg);
107+
108+
bytes = File.ReadAllBytes(filePath).Length;
99109
kiloBytes = MathHelper.ConvertToUnit(bytes, MetricPrefix.Kilo);
100110
101-
Debug.WriteLine($"-> {bytes} {kiloBytes} | {s}");
102-
file = s;
111+
Debug.WriteLine($"Compressed {filePath} -> {newFile} ({kiloBytes})");
112+
113+
filePath = newFile;
103114
}
104-
105-
}
106115
107-
return file;
116+
}*/
117+
118+
return filePath;
108119
}
109120

110121
internal static void OnToastActivated(ToastNotificationActivatedEventArgsCompat compat)

Test/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ public static async Task Main(string[] args)
124124
Console.WriteLine(result.score);*/
125125

126126

127-
foreach (var v in await ImageHelper.FindDirectImages("https://danbooru.donmai.us/posts/3567935")) {
127+
foreach (var v in await ImageHelper.ScanForImages("https://danbooru.donmai.us/posts/3567935")) {
128128
Console.WriteLine(v);
129129
}
130130

0 commit comments

Comments
 (0)