Multi-Platform Package Manager for Stable Diffusion
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

589 lines
19 KiB

using System.Diagnostics.CodeAnalysis;
using System.IO.Compression;
using NLog;
using Octokit;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Helper.Cache;
using StabilityMatrix.Core.Models.Database;
using StabilityMatrix.Core.Models.FileInterfaces;
using StabilityMatrix.Core.Models.Progress;
using StabilityMatrix.Core.Processes;
using StabilityMatrix.Core.Python;
using StabilityMatrix.Core.Services;
namespace StabilityMatrix.Core.Models.Packages;
/// <summary>
/// Base class for packages that are hosted on Github.
/// Author and Name should be the Github username and repository name respectively.
/// </summary>
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
[SuppressMessage("ReSharper", "VirtualMemberNeverOverridden.Global")]
public abstract class BaseGitPackage : BasePackage
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
1 year ago
protected readonly IGithubApiCache GithubApi;
protected readonly ISettingsManager SettingsManager;
protected readonly IDownloadService DownloadService;
protected readonly IPrerequisiteHelper PrerequisiteHelper;
public PyVenvRunner? VenvRunner;
1 year ago
/// <summary>
/// URL of the hosted web page on launch
/// </summary>
protected string WebUrl = string.Empty;
public override string GithubUrl => $"https://github.com/{Author}/{Name}";
public string DownloadLocation =>
Path.Combine(SettingsManager.LibraryDir, "Packages", $"{Name}.zip");
protected string GetDownloadUrl(DownloadPackageVersionOptions versionOptions)
{
if (!string.IsNullOrWhiteSpace(versionOptions.CommitHash))
{
return $"https://github.com/{Author}/{Name}/archive/{versionOptions.CommitHash}.zip";
}
if (!string.IsNullOrWhiteSpace(versionOptions.VersionTag))
{
1 year ago
return $"https://api.github.com/repos/{Author}/{Name}/zipball/{versionOptions.VersionTag}";
}
if (!string.IsNullOrWhiteSpace(versionOptions.BranchName))
{
1 year ago
return $"https://api.github.com/repos/{Author}/{Name}/zipball/{versionOptions.BranchName}";
}
1 year ago
throw new Exception("No download URL available");
}
1 year ago
protected BaseGitPackage(
IGithubApiCache githubApi,
ISettingsManager settingsManager,
IDownloadService downloadService,
IPrerequisiteHelper prerequisiteHelper
)
{
GithubApi = githubApi;
SettingsManager = settingsManager;
DownloadService = downloadService;
PrerequisiteHelper = prerequisiteHelper;
}
public override async Task<DownloadPackageVersionOptions> GetLatestVersion(
bool includePrerelease = false
)
{
if (ShouldIgnoreReleases)
{
return new DownloadPackageVersionOptions
{
IsLatest = true,
IsPrerelease = false,
BranchName = MainBranch
};
}
var release = await GetLatestRelease(includePrerelease).ConfigureAwait(false);
return new DownloadPackageVersionOptions
{
IsLatest = true,
IsPrerelease = release.Prerelease,
VersionTag = release.TagName!
};
}
protected async Task<Release> GetLatestRelease(bool includePrerelease = false)
{
1 year ago
var releases = await GithubApi.GetAllReleases(Author, Name).ConfigureAwait(false);
return includePrerelease ? releases.First() : releases.First(x => !x.Prerelease);
}
1 year ago
public override Task<IEnumerable<Branch>> GetAllBranches()
{
return GithubApi.GetAllBranches(Author, Name);
}
1 year ago
public override Task<IEnumerable<Release>> GetAllReleases()
{
return GithubApi.GetAllReleases(Author, Name);
}
1 year ago
public override Task<IEnumerable<GitCommit>?> GetAllCommits(
string branch,
int page = 1,
int perPage = 10
)
{
return GithubApi.GetAllCommits(Author, Name, branch, page, perPage);
}
1 year ago
public override async Task<PackageVersionOptions> GetAllVersionOptions()
{
var packageVersionOptions = new PackageVersionOptions();
1 year ago
if (!ShouldIgnoreReleases)
{
var allReleases = await GetAllReleases().ConfigureAwait(false);
var releasesList = allReleases.ToList();
if (releasesList.Any())
{
packageVersionOptions.AvailableVersions = releasesList.Select(
r =>
new PackageVersion
{
TagName = r.TagName!,
ReleaseNotesMarkdown = r.Body,
IsPrerelease = r.Prerelease
}
);
}
}
// Branch mode
var allBranches = await GetAllBranches().ConfigureAwait(false);
1 year ago
packageVersionOptions.AvailableBranches = allBranches.Select(
b => new PackageVersion { TagName = $"{b.Name}", ReleaseNotesMarkdown = string.Empty }
);
return packageVersionOptions;
}
/// <summary>
/// Setup the virtual environment for the package.
/// </summary>
[MemberNotNull(nameof(VenvRunner))]
public async Task<PyVenvRunner> SetupVenv(
1 year ago
string installedPackagePath,
string venvName = "venv",
bool forceRecreate = false,
Action<ProcessOutput>? onConsoleOutput = null
1 year ago
)
{
var venvPath = Path.Combine(installedPackagePath, venvName);
if (VenvRunner != null)
{
await VenvRunner.DisposeAsync().ConfigureAwait(false);
}
VenvRunner = new PyVenvRunner(venvPath)
{
WorkingDirectory = installedPackagePath,
EnvironmentVariables = SettingsManager.Settings.EnvironmentVariables,
};
1 year ago
if (!VenvRunner.Exists() || forceRecreate)
{
await VenvRunner.Setup(forceRecreate, onConsoleOutput).ConfigureAwait(false);
}
return VenvRunner;
}
1 year ago
public override async Task<IEnumerable<Release>> GetReleaseTags()
{
1 year ago
var allReleases = await GithubApi.GetAllReleases(Author, Name).ConfigureAwait(false);
return allReleases;
}
1 year ago
public override async Task DownloadPackage(
string installLocation,
DownloadPackageVersionOptions versionOptions,
IProgress<ProgressReport>? progress = null
)
{
if (!string.IsNullOrWhiteSpace(versionOptions.VersionTag))
{
await PrerequisiteHelper
.RunGit(
null,
null,
"clone",
"--branch",
versionOptions.VersionTag,
GithubUrl,
$"\"{installLocation}\""
)
.ConfigureAwait(false);
}
else if (!string.IsNullOrWhiteSpace(versionOptions.BranchName))
{
await PrerequisiteHelper
.RunGit(
null,
null,
"clone",
"--branch",
versionOptions.BranchName,
GithubUrl,
$"\"{installLocation}\""
)
.ConfigureAwait(false);
}
if (!versionOptions.IsLatest && !string.IsNullOrWhiteSpace(versionOptions.CommitHash))
{
await PrerequisiteHelper
.RunGit(installLocation, null, "checkout", versionOptions.CommitHash)
.ConfigureAwait(false);
}
progress?.Report(new ProgressReport(100, message: "Download Complete"));
}
protected Task UnzipPackage(string installLocation, IProgress<ProgressReport>? progress = null)
{
using var zip = ZipFile.OpenRead(DownloadLocation);
var zipDirName = string.Empty;
var totalEntries = zip.Entries.Count;
var currentEntry = 0;
1 year ago
foreach (var entry in zip.Entries)
{
currentEntry++;
if (string.IsNullOrWhiteSpace(entry.Name) && entry.FullName.EndsWith("/"))
{
if (string.IsNullOrWhiteSpace(zipDirName))
{
zipDirName = entry.FullName;
}
1 year ago
var folderPath = Path.Combine(
installLocation,
entry.FullName.Replace(zipDirName, string.Empty)
);
Directory.CreateDirectory(folderPath);
continue;
}
1 year ago
var destinationPath = Path.GetFullPath(
Path.Combine(installLocation, entry.FullName.Replace(zipDirName, string.Empty))
);
entry.ExtractToFile(destinationPath, true);
1 year ago
progress?.Report(
new ProgressReport(
current: Convert.ToUInt64(currentEntry),
total: Convert.ToUInt64(totalEntries)
)
);
}
return Task.CompletedTask;
}
public override async Task<bool> CheckForUpdates(InstalledPackage package)
{
var currentVersion = package.Version;
if (currentVersion is null or { InstalledReleaseVersion: null, InstalledBranch: null })
{
Logger.Warn(
"Could not check updates for package {Name}, version is invalid: {@currentVersion}",
Name,
currentVersion
);
return false;
}
try
{
if (currentVersion.IsReleaseMode)
{
var latestVersion = await GetLatestVersion(currentVersion.IsPrerelease)
.ConfigureAwait(false);
UpdateAvailable =
latestVersion.VersionTag != currentVersion.InstalledReleaseVersion;
return UpdateAvailable;
}
1 year ago
var allCommits = (
await GetAllCommits(currentVersion.InstalledBranch!).ConfigureAwait(false)
1 year ago
)?.ToList();
if (allCommits == null || !allCommits.Any())
{
Logger.Warn("No commits found for {Package}", package.PackageName);
return false;
}
var latestCommitHash = allCommits.First().Sha;
return latestCommitHash != currentVersion.InstalledCommitSha;
}
catch (ApiException e)
{
Logger.Warn(e, "Failed to check for package updates");
return false;
}
}
1 year ago
public override async Task<InstalledPackageVersion> Update(
InstalledPackage installedPackage,
TorchVersion torchVersion,
DownloadPackageVersionOptions versionOptions,
1 year ago
IProgress<ProgressReport>? progress = null,
bool includePrerelease = false,
Action<ProcessOutput>? onConsoleOutput = null
1 year ago
)
{
1 year ago
if (installedPackage.Version == null)
throw new NullReferenceException("Version is null");
if (!Directory.Exists(Path.Combine(installedPackage.FullPath!, ".git")))
{
Logger.Info("not a git repo, initializing...");
progress?.Report(
new ProgressReport(-1f, "Initializing git repo", isIndeterminate: true)
);
await PrerequisiteHelper
.RunGit(installedPackage.FullPath!, onConsoleOutput, "init")
.ConfigureAwait(false);
await PrerequisiteHelper
.RunGit(
installedPackage.FullPath!,
onConsoleOutput,
"remote",
"add",
"origin",
GithubUrl
)
.ConfigureAwait(false);
}
if (!string.IsNullOrWhiteSpace(versionOptions.VersionTag))
{
progress?.Report(new ProgressReport(-1f, "Fetching tags...", isIndeterminate: true));
await PrerequisiteHelper
.RunGit(installedPackage.FullPath!, onConsoleOutput, "fetch", "--tags")
.ConfigureAwait(false);
progress?.Report(
new ProgressReport(
-1f,
$"Checking out {versionOptions.VersionTag}",
isIndeterminate: true
)
);
await PrerequisiteHelper
.RunGit(
installedPackage.FullPath!,
onConsoleOutput,
"checkout",
versionOptions.VersionTag,
"--force"
1 year ago
)
.ConfigureAwait(false);
await InstallPackage(
installedPackage.FullPath!,
torchVersion,
installedPackage.PreferredSharedFolderMethod ?? SharedFolderMethod.Symlink,
versionOptions,
progress,
onConsoleOutput
)
.ConfigureAwait(false);
return new InstalledPackageVersion
{
InstalledReleaseVersion = versionOptions.VersionTag,
IsPrerelease = versionOptions.IsPrerelease
};
}
// fetch
progress?.Report(new ProgressReport(-1f, "Fetching data...", isIndeterminate: true));
await PrerequisiteHelper
.RunGit(installedPackage.FullPath!, onConsoleOutput, "fetch")
1 year ago
.ConfigureAwait(false);
if (versionOptions.IsLatest)
{
// checkout
progress?.Report(
new ProgressReport(
-1f,
$"Checking out {installedPackage.Version.InstalledBranch}...",
isIndeterminate: true
)
);
await PrerequisiteHelper
.RunGit(
installedPackage.FullPath!,
onConsoleOutput,
"checkout",
versionOptions.BranchName,
"--force"
)
.ConfigureAwait(false);
// pull
progress?.Report(new ProgressReport(-1f, "Pulling changes...", isIndeterminate: true));
await PrerequisiteHelper
.RunGit(
installedPackage.FullPath!,
onConsoleOutput,
"pull",
"origin",
installedPackage.Version.InstalledBranch
)
.ConfigureAwait(false);
}
else
{
// checkout
progress?.Report(
new ProgressReport(
-1f,
$"Checking out {installedPackage.Version.InstalledBranch}...",
isIndeterminate: true
)
);
await PrerequisiteHelper
.RunGit(
installedPackage.FullPath!,
onConsoleOutput,
"checkout",
versionOptions.CommitHash,
"--force"
)
.ConfigureAwait(false);
}
await InstallPackage(
1 year ago
installedPackage.FullPath,
torchVersion,
installedPackage.PreferredSharedFolderMethod ?? SharedFolderMethod.Symlink,
versionOptions,
progress,
onConsoleOutput
1 year ago
)
.ConfigureAwait(false);
return new InstalledPackageVersion
{
InstalledBranch = versionOptions.BranchName,
InstalledCommitSha = versionOptions.CommitHash,
IsPrerelease = versionOptions.IsPrerelease
};
}
1 year ago
public override Task SetupModelFolders(
DirectoryPath installDirectory,
SharedFolderMethod sharedFolderMethod
)
{
if (sharedFolderMethod == SharedFolderMethod.Symlink && SharedFolders is { } folders)
{
return StabilityMatrix.Core.Helper.SharedFolders.UpdateLinksForPackage(
1 year ago
folders,
SettingsManager.ModelsDirectory,
installDirectory
);
}
return Task.CompletedTask;
}
public override Task UpdateModelFolders(
1 year ago
DirectoryPath installDirectory,
SharedFolderMethod sharedFolderMethod
)
{
if (sharedFolderMethod == SharedFolderMethod.Symlink && SharedFolders is { } sharedFolders)
{
return StabilityMatrix.Core.Helper.SharedFolders.UpdateLinksForPackage(
sharedFolders,
SettingsManager.ModelsDirectory,
installDirectory
);
}
return Task.CompletedTask;
}
1 year ago
public override Task RemoveModelFolderLinks(
DirectoryPath installDirectory,
SharedFolderMethod sharedFolderMethod
)
{
if (SharedFolders is not null && sharedFolderMethod == SharedFolderMethod.Symlink)
{
StabilityMatrix.Core.Helper.SharedFolders.RemoveLinksForPackage(
SharedFolders,
installDirectory
);
}
return Task.CompletedTask;
}
public override Task SetupOutputFolderLinks(DirectoryPath installDirectory)
{
if (SharedOutputFolders is { } sharedOutputFolders)
{
return StabilityMatrix.Core.Helper.SharedFolders.UpdateLinksForPackage(
sharedOutputFolders,
SettingsManager.ImagesDirectory,
installDirectory,
recursiveDelete: true
);
}
return Task.CompletedTask;
}
public override Task RemoveOutputFolderLinks(DirectoryPath installDirectory)
{
if (SharedOutputFolders is { } sharedOutputFolders)
{
StabilityMatrix.Core.Helper.SharedFolders.RemoveLinksForPackage(
sharedOutputFolders,
installDirectory
);
}
return Task.CompletedTask;
}
// Send input to the running process.
public virtual void SendInput(string input)
{
var process = VenvRunner?.Process;
if (process == null)
{
Logger.Warn("No process running for {Name}", Name);
return;
}
process.StandardInput.WriteLine(input);
}
1 year ago
public virtual async Task SendInputAsync(string input)
{
var process = VenvRunner?.Process;
if (process == null)
{
Logger.Warn("No process running for {Name}", Name);
return;
}
await process.StandardInput.WriteLineAsync(input).ConfigureAwait(false);
}
/// <inheritdoc />
public override void Shutdown()
{
if (VenvRunner is not null)
{
VenvRunner.Dispose();
VenvRunner = null;
}
}
1 year ago
/// <inheritdoc />
public override async Task WaitForShutdown()
{
if (VenvRunner is not null)
{
await VenvRunner.DisposeAsync().ConfigureAwait(false);
VenvRunner = null;
}
}
}