-
-
Notifications
You must be signed in to change notification settings - Fork 551
Expand file tree
/
Copy pathModelImportService.cs
More file actions
371 lines (321 loc) · 13.1 KB
/
ModelImportService.cs
File metadata and controls
371 lines (321 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
using AsyncAwaitBestPractices;
using Avalonia.Controls.Notifications;
using Injectio.Attributes;
using StabilityMatrix.Avalonia.ViewModels.Inference;
using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.Api;
using StabilityMatrix.Core.Models.Api.OpenModelsDb;
using StabilityMatrix.Core.Models.FileInterfaces;
using StabilityMatrix.Core.Models.Progress;
using StabilityMatrix.Core.Services;
using Dispatcher = Avalonia.Threading.Dispatcher;
namespace StabilityMatrix.Avalonia.Services;
[RegisterSingleton<IModelImportService, ModelImportService>]
public class ModelImportService(
IDownloadService downloadService,
INotificationService notificationService,
ITrackedDownloadService trackedDownloadService
) : IModelImportService
{
public static async Task<FilePath> SaveCmInfo(
CivitModel model,
CivitModelVersion modelVersion,
CivitFile modelFile,
DirectoryPath downloadDirectory,
string? fileNameOverride = null,
SamplerCardViewModel? samplerCardVm = null
)
{
var modelFileName = fileNameOverride ?? Path.GetFileNameWithoutExtension(modelFile.Name);
InferenceDefaults? inferenceDefaults = null;
if (samplerCardVm != null)
{
inferenceDefaults = new InferenceDefaults
{
Sampler = samplerCardVm.SelectedSampler,
Scheduler = samplerCardVm.SelectedScheduler,
CfgScale = samplerCardVm.CfgScale,
Steps = samplerCardVm.Steps,
Width = samplerCardVm.Width,
Height = samplerCardVm.Height,
};
}
var modelInfo = new ConnectedModelInfo(
model,
modelVersion,
modelFile,
DateTime.UtcNow,
inferenceDefaults
);
await modelInfo.SaveJsonToDirectory(downloadDirectory, modelFileName);
var jsonName = $"{modelFileName}.cm-info.json";
return downloadDirectory.JoinFile(jsonName);
}
/// <summary>
/// Saves the preview image to the same directory as the model file
/// </summary>
/// <param name="modelVersion"></param>
/// <param name="modelFilePath"></param>
/// <returns>The file path of the saved preview image</returns>
public async Task<FilePath?> SavePreviewImage(CivitModelVersion modelVersion, FilePath modelFilePath)
{
// Skip if model has no images
if (modelVersion.Images == null || modelVersion.Images.Count == 0)
{
return null;
}
var image = modelVersion.Images.FirstOrDefault(x => x.Type == "image");
if (image is null)
return null;
var imageExtension = Path.GetExtension(image.Url).TrimStart('.');
if (imageExtension is "jpg" or "jpeg" or "png")
{
var imageDownloadPath = modelFilePath.Directory!.JoinFile(
$"{modelFilePath.NameWithoutExtension}.preview.{imageExtension}"
);
var imageTask = downloadService.DownloadToFileAsync(image.Url, imageDownloadPath);
await notificationService.TryAsync(imageTask, "Could not download preview image");
return imageDownloadPath;
}
return null;
}
public async Task DoImport(
CivitModel model,
DirectoryPath downloadFolder,
CivitModelVersion? selectedVersion = null,
CivitFile? selectedFile = null,
string? fileNameOverride = null,
SamplerCardViewModel? inferenceDefaults = null,
IProgress<ProgressReport>? progress = null,
Func<Task>? onImportComplete = null,
Func<Task>? onImportCanceled = null,
Func<Task>? onImportFailed = null
)
{
// Get latest version
var modelVersion = selectedVersion ?? model.ModelVersions?.FirstOrDefault();
if (modelVersion is null)
{
notificationService.Show(
new Notification(
"Model has no versions available",
"This model has no versions available for download",
NotificationType.Warning
)
);
return;
}
// Get latest version file
var modelFile =
selectedFile ?? modelVersion.Files?.FirstOrDefault(x => x.Type == CivitFileType.Model);
if (modelFile is null)
{
notificationService.Show(
new Notification(
"Model has no files available",
"This model has no files available for download",
NotificationType.Warning
)
);
return;
}
if (fileNameOverride != null && (fileNameOverride.Contains("\\") || fileNameOverride.Contains("/")))
{
// figure out the folder path to add to downloadFolder
var lastIndex = fileNameOverride.LastIndexOfAny(['\\', '/']);
if (lastIndex >= 0)
{
// Extract folder path and file name
var folderPath = fileNameOverride.Substring(0, lastIndex);
fileNameOverride = fileNameOverride.Substring(lastIndex + 1);
// Join with download folder
downloadFolder = downloadFolder.JoinDir(folderPath);
}
}
// Folders might be missing if user didn't install any packages yet
downloadFolder.Create();
var originalFileName =
fileNameOverride == null
? modelFile.Name
: $@"{fileNameOverride}{Path.GetExtension(modelFile.Name)}";
// Fix invalid chars in FileName
originalFileName = Path.GetInvalidFileNameChars()
.Aggregate(originalFileName, (current, c) => current.Replace(c, '_'));
// Generate unique file name if it already exists
var uniqueFileName = GenerateUniqueFileName(downloadFolder.ToString(), originalFileName);
if (!uniqueFileName.Equals(originalFileName, StringComparison.Ordinal))
{
Dispatcher.UIThread.Post(() =>
{
notificationService.Show(
new Notification(
"File renamed",
$"A file with the name \"{originalFileName}\" already exists. The model will be saved as \"{uniqueFileName}\"."
)
);
});
}
var downloadPath = downloadFolder.JoinFile(uniqueFileName);
// Download model info and preview first
var cmInfoPath = await SaveCmInfo(
model,
modelVersion,
modelFile,
downloadFolder,
Path.GetFileNameWithoutExtension(uniqueFileName),
inferenceDefaults
);
var previewImagePath = await SavePreviewImage(modelVersion, downloadPath);
// Create tracked download
var download = trackedDownloadService.NewDownload(modelFile.DownloadUrl, downloadPath);
// Add hash info
download.ExpectedHashSha256 = modelFile.Hashes.SHA256;
// Add files to cleanup list
download.ExtraCleanupFileNames.Add(cmInfoPath);
if (previewImagePath is not null)
{
download.ExtraCleanupFileNames.Add(previewImagePath);
}
// Attach for progress updates
download.ProgressUpdate += (s, e) =>
{
progress?.Report(e);
};
download.ProgressStateChanged += (s, e) =>
{
if (e == ProgressState.Success)
{
onImportComplete?.Invoke().SafeFireAndForget();
}
else if (e == ProgressState.Cancelled)
{
onImportCanceled?.Invoke().SafeFireAndForget();
}
else if (e == ProgressState.Failed)
{
onImportFailed?.Invoke().SafeFireAndForget();
}
};
// Add hash context action
download.ContextAction = CivitPostDownloadContextAction.FromCivitFile(modelFile);
await trackedDownloadService.TryStartDownload(download);
}
public Task DoOpenModelDbImport(
OpenModelDbKeyedModel model,
OpenModelDbResource resource,
DirectoryPath downloadFolder,
Action<TrackedDownload>? configureDownload = null
)
{
// todo: maybe can get actual filename from url?
ArgumentException.ThrowIfNullOrEmpty(model.Id, nameof(model));
ArgumentException.ThrowIfNullOrEmpty(resource.Type, nameof(resource));
var modelFileName = $"{model.Id}.{resource.Type}";
var modelUris = resource.Urls?.Select(u => new Uri(u, UriKind.Absolute)).ToArray();
if (modelUris is null || modelUris.Length == 0)
{
notificationService.Show(
new Notification(
"Model has no download links",
"This model has no download links available",
NotificationType.Warning
)
);
return Task.CompletedTask;
}
return DoCustomImport(
modelUris,
modelFileName,
downloadFolder,
model.Images?.SelectImageAbsoluteUris().FirstOrDefault(),
configureDownload: configureDownload,
connectedModelInfo: new ConnectedModelInfo(model, resource, DateTimeOffset.Now)
);
}
public async Task DoCustomImport(
IEnumerable<Uri> modelUris,
string modelFileName,
DirectoryPath downloadFolder,
Uri? previewImageUri = null,
string? previewImageFileExtension = null,
ConnectedModelInfo? connectedModelInfo = null,
Action<TrackedDownload>? configureDownload = null
)
{
// Folders might be missing if user didn't install any packages yet
downloadFolder.Create();
// Fix invalid chars in FileName
var modelBaseFileName = Path.GetFileNameWithoutExtension(modelFileName);
modelBaseFileName = Path.GetInvalidFileNameChars()
.Aggregate(modelBaseFileName, (current, c) => current.Replace(c, '_'));
var modelFileExtension = Path.GetExtension(modelFileName);
var downloadPath = downloadFolder.JoinFile(modelBaseFileName + modelFileExtension);
// Save model info and preview image first if available
var cleanupFilePaths = new List<string>();
if (connectedModelInfo is not null)
{
await connectedModelInfo.SaveJsonToDirectory(downloadFolder, modelBaseFileName);
cleanupFilePaths.Add(
downloadFolder.JoinFile(modelBaseFileName + ConnectedModelInfo.FileExtension)
);
}
if (previewImageUri is not null)
{
if (previewImageFileExtension is null)
{
previewImageFileExtension = Path.GetExtension(previewImageUri.LocalPath);
if (string.IsNullOrEmpty(previewImageFileExtension))
{
throw new InvalidOperationException(
"Unable to get preview image file extension from from Uri, and no file extension provided"
);
}
}
var previewImageDownloadPath = downloadFolder.JoinFile(
modelBaseFileName + ".preview" + previewImageFileExtension
);
await notificationService.TryAsync(
downloadService.DownloadToFileAsync(previewImageUri.ToString(), previewImageDownloadPath),
"Could not download preview image"
);
cleanupFilePaths.Add(previewImageDownloadPath);
}
// Create tracked download with first URL, storing others as fallbacks
// If download fails, the TrackedDownloadService will attempt to use fallback URLs
var uriList = modelUris.ToList();
var primaryUri = uriList.First();
var fallbackUris = uriList.Skip(1).ToList();
var download = trackedDownloadService.NewDownload(primaryUri, downloadPath);
// Store fallback URLs for retry attempts
if (fallbackUris.Count > 0)
{
download.FallbackUris = fallbackUris;
}
// Add hash info
// download.ExpectedHashSha256 = modelFile.Hashes.SHA256;
// Add files to cleanup list
download.ExtraCleanupFileNames.AddRange(cleanupFilePaths);
// Configure
configureDownload?.Invoke(download);
// Add hash context action
// download.ContextAction = CivitPostDownloadContextAction.FromCivitFile(modelFile);
await trackedDownloadService.TryStartDownload(download);
}
private string GenerateUniqueFileName(string folder, string fileName)
{
var fullPath = Path.Combine(folder, fileName);
if (!File.Exists(fullPath))
return fileName;
var name = Path.GetFileNameWithoutExtension(fileName);
var extension = Path.GetExtension(fileName);
var count = 1;
string newFileName;
do
{
newFileName = $"{name} ({count}){extension}";
fullPath = Path.Combine(folder, newFileName);
count++;
} while (File.Exists(fullPath));
return newFileName;
}
}