Skip to content

Commit add06d5

Browse files
committed
replace hard-coded file variant paths with a dynamically created variant paths
1 parent 641e483 commit add06d5

File tree

11 files changed

+67
-161
lines changed

11 files changed

+67
-161
lines changed

BlazorDiffusion.ServiceInterface/ArtifactMetaServices.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public async Task<object> Get(DownloadArtifact request)
6767
var artifact = !string.IsNullOrEmpty(request.RefId)
6868
? Db.Single<Artifact>(x => x.RefId == request.RefId)
6969
: null;
70-
if (artifact?.FilePathLarge == null)
70+
if (artifact?.FilePath == null)
7171
return HttpError.NotFound("File not found");
7272

7373
jobs.RunCommand<RecordAnalyticsCommand>(new RecordAnalytics {
@@ -81,7 +81,7 @@ public async Task<object> Get(DownloadArtifact request)
8181
});
8282

8383
long? contentLength = null;
84-
var url = appConfig.AiServerBaseUrl.CombineWith(artifact.FilePathLarge);
84+
var url = appConfig.AiServerBaseUrl.CombineWith(artifact.FilePath);
8585
var imageBytes = await url.GetBytesFromUrlAsync(responseFilter:res => contentLength = res.GetContentLength());
8686
var headerValue = $"attachment; {HttpExt.GetDispositionFileName(artifact.FileName)}; " +
8787
(contentLength != null ? $"size={contentLength}; " : "") +

BlazorDiffusion.ServiceInterface/CreativeServerExtensions.cs

+1
Original file line numberDiff line numberDiff line change
@@ -98,3 +98,4 @@ public static bool IsOwnerOrModerator(this IRequest? req, int? ownerId)
9898
return true;
9999
}
100100
}
101+

BlazorDiffusion.ServiceInterface/CreativeService.cs

+8-10
Original file line numberDiff line numberDiff line change
@@ -109,9 +109,9 @@ public object Post(CreateCreativeCallback request)
109109
FileName = item.FileName,
110110
Width = (int)createCreative.Width!,
111111
Height = (int)createCreative.Height!,
112-
FilePathSmall = $"/variants/{variant}=118".CombineWith(item.Url.RightPart("/artifacts")),
113-
FilePathMedium = $"/variants/{variant}=288".CombineWith(item.Url.RightPart("/artifacts")),
114-
FilePathLarge = item.Url,
112+
// FilePathSmall = $"/variants/{variant}=118".CombineWith(item.Url.RightPart("/artifacts")),
113+
// FilePathMedium = $"/variants/{variant}=288".CombineWith(item.Url.RightPart("/artifacts")),
114+
// FilePathLarge = item.Url,
115115
//Image details updated in SyncArtifactsCommand
116116
});
117117
}
@@ -417,9 +417,9 @@ private int PersistCreative(CreateCreative request,
417417
Seed = x.Seed,
418418
FileName = x.FileName,
419419
FilePath = x.FilePath,
420-
FilePathSmall = x.FilePathSmall,
421-
FilePathMedium = x.FilePathMedium,
422-
FilePathLarge = x.FilePathLarge,
420+
// FilePathSmall = x.FilePathSmall,
421+
// FilePathMedium = x.FilePathMedium,
422+
// FilePathLarge = x.FilePathLarge,
423423
ContentType = MimeTypes.ImagePng,
424424
ContentLength = x.ContentLength,
425425
RefId = Guid.NewGuid().ToString("D"),
@@ -530,10 +530,8 @@ public async Task Delete(HardDeleteCreative request)
530530
transaction.Commit();
531531

532532
var artifactPaths = artifacts
533-
.Where(x => x.FilePathLarge != null)
534-
.Select(x => x.FilePathLarge!).ToList();
535-
var api = await aiClient.Client.ApiAsync(new DeleteFiles
536-
{
533+
.Select(x => x.FilePath).ToList();
534+
var api = await aiClient.Client.ApiAsync(new DeleteFiles {
537535
Paths = artifactPaths,
538536
});
539537
log.LogInformation("DeleteFiles:\n{Json}", api.Response.ToJson());

BlazorDiffusion.ServiceInterface/ImageDetails.cs

-94
Original file line numberDiff line numberDiff line change
@@ -203,98 +203,4 @@ public static int BackgroundCompare(string rgba1, string rgba2)
203203
}
204204
return 0xFFFFFF;
205205
}
206-
207-
public static async Task<MemoryStream> CropAndResizeAsync(Stream inStream, int width, int height, IImageFormat format)
208-
{
209-
var outStream = new MemoryStream();
210-
using (var image = await Image.LoadAsync(inStream))
211-
{
212-
var clone = image.Clone(context => context
213-
.Resize(new ResizeOptions {
214-
Mode = ResizeMode.Crop,
215-
Size = new Size(width, height),
216-
}));
217-
await clone.SaveAsync(outStream, format);
218-
}
219-
outStream.Position = 0;
220-
return outStream;
221-
}
222-
223-
public static async Task ResizeArtifactsAsync(this IVirtualFiles vfs, Artifact artifact)
224-
{
225-
var file = vfs.AssertFile(artifact.FilePath);
226-
using var stream = file.OpenRead();
227-
using var image = await Image.LoadAsync(stream);
228-
await ResizeArtifactsAsync(vfs, artifact, image);
229-
}
230-
231-
public static async Task ResizeArtifactsAsync(this IVirtualFiles vfs, Artifact artifact, Image image, Microsoft.Extensions.Logging.ILogger? log = null)
232-
{
233-
var sw = Stopwatch.StartNew();
234-
var tasks = new List<(MemoryStream ms, Task task)>();
235-
string basePath = artifact.FilePath.WithoutExtension();
236-
237-
// Small 118x118 or 118x207
238-
if (artifact.FilePathSmall == null)
239-
{
240-
var width = artifact.Width > artifact.Height
241-
? 207
242-
: 118;
243-
var height = artifact.Height > artifact.Width
244-
? 207
245-
: 118;
246-
using var clone = image.Clone(context => context.Resize(new ResizeOptions
247-
{
248-
Mode = ResizeMode.Crop,
249-
Size = new Size(width, height),
250-
}));
251-
artifact.FilePathSmall = $"{basePath}_{width}.webp";
252-
var ms = MemoryStreamFactory.GetStream();
253-
await clone.SaveAsWebpAsync(ms);
254-
tasks.Add((ms, vfs.WriteFileAsync(artifact.FilePathSmall, ms)));
255-
}
256-
257-
// Medium 288x288 or 288x504
258-
if (artifact.FilePathMedium == null)
259-
{
260-
var width = artifact.Width > artifact.Height
261-
? 504
262-
: 288;
263-
var height = artifact.Height > artifact.Width
264-
? 504
265-
: 288;
266-
using var clone = image.Clone(context => context.Resize(new ResizeOptions
267-
{
268-
Mode = ResizeMode.Crop,
269-
Size = new Size(width, height),
270-
}));
271-
272-
artifact.FilePathMedium = $"{basePath}_{width}.webp";
273-
var ms = MemoryStreamFactory.GetStream();
274-
await clone.SaveAsWebpAsync(ms);
275-
tasks.Add((ms, vfs.WriteFileAsync(artifact.FilePathMedium, ms)));
276-
}
277-
278-
// Large Original Size
279-
if (artifact.FilePathLarge == null)
280-
{
281-
artifact.FilePathLarge = $"{basePath}_{artifact.Width}.webp";
282-
var ms = MemoryStreamFactory.GetStream();
283-
await image.SaveAsWebpAsync(ms);
284-
tasks.Add((ms, vfs.WriteFileAsync(artifact.FilePathLarge, ms)));
285-
}
286-
287-
// Run All Expensive I/O Ops concurrently
288-
if (tasks.Count > 0)
289-
{
290-
log?.LogInformation("Resize {Count} Artifacts: {ms}ms", tasks.Count, sw.ElapsedMilliseconds);
291-
292-
sw.Restart();
293-
294-
await Task.WhenAll(tasks.Select(x => x.task));
295-
tasks.ForEach(x => x.ms.Dispose());
296-
297-
log?.LogInformation("Write {Count} Resized Artifacts: {ms}ms", tasks.Count, sw.ElapsedMilliseconds);
298-
}
299-
}
300206
}

BlazorDiffusion.ServiceInterface/MigrationServices.cs

+6-6
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public async Task<object> Any(MigrateOldArtifacts request)
2727
{
2828
var limit = request.Limit ?? 10;
2929
var artifacts = Db.Select(Db.From<Artifact>()
30-
.Where(x => x.FilePath.EndsWith(".png") || !x.FilePathSmall!.StartsWith("/variant"))
30+
.Where(x => x.FilePath.EndsWith(".png"))
3131
.OrderBy(x => x.Id)
3232
.Take(limit));
3333

@@ -59,15 +59,15 @@ public async Task<object> Any(MigrateOldArtifacts request)
5959
{
6060
var variant = artifact.Height > artifact.Width ? "height" : "width";
6161
var fileName = newFilePath.LastRightPart('/');
62-
var filePathSmall = $"/variants/{variant}=118".CombineWith(newFilePath.RightPart("/artifacts"));
63-
var filePathMedium = $"/variants/{variant}=288".CombineWith(newFilePath.RightPart("/artifacts"));
62+
// var filePathSmall = $"/variants/{variant}=118".CombineWith(newFilePath.RightPart("/artifacts"));
63+
// var filePathMedium = $"/variants/{variant}=288".CombineWith(newFilePath.RightPart("/artifacts"));
6464
Db.UpdateOnly(() => new Artifact
6565
{
6666
FileName = fileName,
6767
FilePath = newFilePath,
68-
FilePathSmall = filePathSmall,
69-
FilePathMedium = filePathMedium,
70-
FilePathLarge = newFilePath,
68+
// FilePathSmall = filePathSmall,
69+
// FilePathMedium = filePathMedium,
70+
// FilePathLarge = newFilePath,
7171
}, where: a => a.Id == artifact.Id);
7272
to.Results.Add(newFilePath);
7373
log.LogInformation($"Migrated {artifact.Id} to {newFilePath}");

BlazorDiffusion.ServiceInterface/Recurring/SyncArtifactsCommand.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ protected override async Task RunAsync(CancellationToken token)
3030
{
3131
try
3232
{
33-
var artifactUrl = appConfig.AiServerBaseUrl.CombineWith(artifact.FilePathLarge);
33+
var artifactUrl = appConfig.AiServerBaseUrl.CombineWith(artifact.FilePath);
3434
var stream = await artifactUrl.GetStreamFromUrlAsync(
3535
responseFilter:res => artifact.ContentLength = res.Content.Headers.ContentLength ?? 0, token:token);
3636

BlazorDiffusion.ServiceModel/Artifacts.cs

+6-3
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,12 @@ public class Artifact : AuditBase
4848
public int Score { get; set; }
4949
public int Rank { get; set; }
5050
public string RefId { get; set; }
51-
public string? FilePathSmall { get; set; } // 118x118 or 118x207
52-
public string? FilePathMedium { get; set; } // 288x288 or 288x504
53-
public string? FilePathLarge { get; set; } // Original Size in .webp
51+
52+
// No longer using hard-coded paths
53+
// public string? FilePathSmall { get; set; } // 118x118 or 118x207
54+
// public string? FilePathMedium { get; set; } // 288x288 or 288x504
55+
// public string? FilePathLarge { get; set; } // Original Size in .webp
56+
5457
public Dictionary<string,string> Versions { get; set; } // Alternative Asset Versions
5558
}
5659

BlazorDiffusion.Tests/ImageDetailsTests.cs

-18
Original file line numberDiff line numberDiff line change
@@ -67,24 +67,6 @@ public void Compare_calculating_dominant_color()
6767
appFilesDir.Print();
6868
}
6969

70-
[Test]
71-
public async Task ResizeImages()
72-
{
73-
var appFilesDir = Path.GetFullPath("../../../App_Files");
74-
var avatarsDir = Path.Combine(appFilesDir, "avatars");
75-
var outDir = Path.Combine(avatarsDir, "out").AssertDir();
76-
77-
foreach (var file in new DirectoryInfo(avatarsDir).GetFiles())
78-
{
79-
using var fs = file.OpenRead();
80-
var ms = await ImageUtils.CropAndResizeAsync(fs, 128, 128, PngFormat.Instance);
81-
var outFile = Path.Combine(outDir, file.Name.WithoutExtension() + "_128" + file.Extension);
82-
var outFs = new FileStream(outFile, FileMode.OpenOrCreate);
83-
ms.Position = 0;
84-
await ms.CopyToAsync(outFs);
85-
}
86-
}
87-
8870

8971
[Test]
9072
[TestCase("#888888FF", "#898888FF", 1)]

BlazorDiffusion/Components/Pages/ArtView.razor

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
<HeadCard Title="@Creative.UserPrompt"
1313
Summary="summary_large_image"
1414
Url="@AppConfig.WwwBaseUrl.CombineWith($"/artifacts/{Id}/{Slug}")"
15-
ImagePath="@(Artifact!.FilePathLarge ?? Artifact.FilePath)"
15+
ImagePath="@(Artifact!.FilePath)"
1616
Description="@MetaDescription" />
1717
</HeadContent>
1818

BlazorDiffusion/UserState.cs

+18-15
Original file line numberDiff line numberDiff line change
@@ -285,26 +285,29 @@ public static ArtifactSize GetSize(int? minSize = null) => minSize == null
285285
? ArtifactSize.Large
286286
: ArtifactSize.Medium;
287287

288-
public static string? GetFilePath(this Artifact artifact, ArtifactSize size) => size switch {
289-
ArtifactSize.Small => artifact.FilePathSmall,
290-
ArtifactSize.Medium => artifact.FilePathMedium,
291-
ArtifactSize.Large => artifact.FilePathLarge,
292-
_ => artifact.FilePath,
293-
};
294-
288+
public static string GetVariantPath(Artifact artifact, int minSize, int maxSize)
289+
{
290+
var path = artifact.FilePath.RightPart("/artifacts");
291+
if (artifact.Height > artifact.Width)
292+
return $"/variants/width={minSize},height={maxSize}".CombineWith(path);
293+
if (artifact.Width > artifact.Height)
294+
return $"/variants/width={maxSize},height={minSize}".CombineWith(path);
295+
return $"/variants/width={minSize}".CombineWith(path);
296+
}
297+
295298
public static string GetFilePath(string cdnPath, Artifact artifact, int? minSize=null)
296299
{
297300
var size = GetSize(minSize);
298-
var cachedFilePath = artifact.GetFilePath(size);
299-
return cachedFilePath != null
300-
? cdnPath + cachedFilePath
301-
: artifact.GetResizedPath(size);
301+
var variantPath = size == ArtifactSize.Small
302+
? GetVariantPath(artifact, 118, 207)
303+
: size == ArtifactSize.Medium
304+
? GetVariantPath(artifact, 288, 504)
305+
: null;
306+
if (variantPath == null)
307+
return cdnPath.CombineWith(artifact.FilePath);
308+
return cdnPath.CombineWith(variantPath);
302309
}
303310

304-
public static string GetResizedPath(this Artifact artifact, ArtifactSize size) =>
305-
$"/artifacts/{artifact.Id}/resized/{size.ToString().ToLower()}";
306-
307-
308311
public static int GetAlbumCoverArtifactId(this AlbumResult album)
309312
{
310313
return album.PrimaryArtifactId != null && album.ArtifactIds.Contains(album.PrimaryArtifactId.Value)

BlazorDiffusion/wwwroot/mjs/store.mjs

+24-11
Original file line numberDiff line numberDiff line change
@@ -469,20 +469,33 @@ export class Store {
469469
return size
470470
}
471471

472-
/** @param {Artifact} artifact
472+
/** @param {Artifact} artifact
473+
* @param {number} minSize
474+
* @param {number} maxSize */
475+
getVariantPath(artifact, minSize, maxSize) {
476+
const path = rightPart(artifact.filePath, "/artifacts")
477+
if (artifact.height > artifact.width)
478+
return combinePaths(`/variants/width=${minSize},height=${maxSize}`, path)
479+
if (artifact.width > artifact.height)
480+
return combinePaths(`/variants/width=${maxSize},height=${minSize}`, path)
481+
return combinePaths(`/variants/width=${minSize}`, path)
482+
}
483+
484+
/** @param {string} cdnPath
485+
* @param {Artifact} artifact
473486
* @param {number?} minSize */
474487
getFilePath(cdnPath, artifact, minSize=null) {
475488
const size = this.getSize(minSize)
476-
const cachedFilePath = artifact[`filePath${size}`]
477-
return cachedFilePath
478-
? cdnPath + cachedFilePath
479-
: this.getResizedPath(artifact, size)
480-
}
481-
482-
/** @param {Artifact} artifact
483-
* @param {string} size */
484-
getResizedPath(artifact, size) {
485-
return `/artifacts/${artifact.id}/resized/${size.toLowerCase()}`
489+
const variantPath = size === 'Small'
490+
? this.getVariantPath(artifact, 118, 207)
491+
: size === 'Medium'
492+
? this.getVariantPath(artifact, 288, 504)
493+
: null
494+
console.log('getFilePath', this.AssetsBasePath, minSize, size, variantPath, artifact.filePath)
495+
496+
if (!variantPath)
497+
return combinePaths(cdnPath, artifact.filePath)
498+
return combinePaths(cdnPath, variantPath)
486499
}
487500

488501
/** @param {Artifact} artifact */

0 commit comments

Comments
 (0)