public async void ReloadImage(bool allowFail = true) // Returns false on error { string path = Program.lastImgPath; DialogForm loadingBox = new DialogForm($"Loading {Path.GetFileName(path)}", 20); await Task.Delay(10); try { File.Copy(path, Paths.tempImgPath, true); bool fillAlpha = !bool.Parse(Config.Get("alpha")); await ImageProcessing.ConvertImage(path, ImageProcessing.Format.PngRaw, fillAlpha, ImageProcessing.ExtMode.UseNew, false, Paths.tempImgPath, true); previewImg.Image = ImgUtils.GetImage(Paths.tempImgPath); PreviewUI.currentScale = 1; previewImg.ZoomToFit(); lastZoom = previewImg.Zoom; } catch (Exception e) { Logger.Log("Failed to reload image from source path - Maybe image is from clipboard or has been deleted. " + e.Message); if (!allowFail) { Logger.ErrorMessage("Failed to load image:", e); failed = true; } } if (loadingBox != null) { loadingBox.Close(); } }
public static async Task ConvertNcnnModel(string modelPath) { string modelName = Path.GetFileName(modelPath); ncnnDir = Path.Combine(Config.Get("modelPath"), ".ncnn"); Directory.CreateDirectory(ncnnDir); string outPath = Path.Combine(ncnnDir, Path.ChangeExtension(modelName, null)); Logger.Log("Checking for NCNN model: " + outPath); if (IOUtils.GetAmountOfFiles(outPath, false) < 2) { Logger.Log("Running model converter..."); DialogForm dialog = new DialogForm("Converting ESRGAN model to NCNN format..."); await RunConverter(modelPath); string moveFrom = Path.Combine(Config.Get("esrganPath"), Path.ChangeExtension(modelName, null)); Logger.Log("Moving " + moveFrom + " to " + outPath); IOUtils.Copy(moveFrom, outPath, "*", true); Directory.Delete(moveFrom, true); dialog.Close(); } else { Logger.Log("NCNN Model is cached - Skipping conversion."); } ESRGAN.currentNcnnModel = outPath; }
private async void offlineInterpBtn_Click(object sender, EventArgs e) { if (MainUIHelper.currentMode == Mode.Interp) { try { string mdl1 = Program.currentModel1; string mdl2 = Program.currentModel2; if (string.IsNullOrWhiteSpace(mdl1) || string.IsNullOrWhiteSpace(mdl2)) { return; } ModelData mdl = new ModelData(mdl1, mdl2, ModelData.ModelMode.Interp, interpValue); DialogForm loadingForm = new DialogForm("Interpolating..."); await Task.Delay(50); string outPath = ESRGAN.Interpolate(mdl); loadingForm.Close(); Program.ShowMessage("Saved interpolated model to:\n\n" + outPath); } catch (Exception interpException) { Logger.ErrorMessage("Error trying to create an interpolated model:", interpException); Program.CloseTempForms(); } } else { Program.ShowMessage("Please select \"Interpolate Between Two Models\" and select two models."); } }
static async Task DownloadAndInstall(int version, string filename, bool showDialog = true) { string savePath = Path.Combine(IOUtils.GetAppDataDir(), filename); string url = $"https://dl.nmkd.de/cupscale/shippedfiles/{version}/{filename}"; Logger.Log($"[Installer] Downloading {url}"); var client = new WebClient(); currentDlDialog = new DialogForm($"Downloading {filename}…"); sw.Restart(); client.DownloadProgressChanged += DownloadProgressChanged; await client.DownloadFileTaskAsync(new Uri(url), savePath); if (Path.GetExtension(filename).ToLower() == ".7z") // Only run extractor if it's a 7z archive { if (currentDlDialog != null) { currentDlDialog.ChangeText($"Installing {filename}..."); } await UnSevenzip(Path.Combine(IOUtils.GetAppDataDir(), filename)); } if (currentDlDialog != null) { currentDlDialog.Close(); } currentDlDialog = null; }
public static async Task Install() { Program.mainForm.Enabled = false; DialogForm dialog = new DialogForm("Installing resources...\nThis only needs to be done once."); await Task.Delay(20); Directory.CreateDirectory(path); path7za = Path.Combine(path, "7za.exe"); File.WriteAllBytes(path7za, Resources.x64_7za); File.WriteAllBytes(Path.Combine(IOUtils.GetAppDataDir(), "esrgan.7z"), Resources.esrgan); File.WriteAllBytes(Path.Combine(IOUtils.GetAppDataDir(), "ncnn.7z"), Resources.esrgan_ncnn); File.WriteAllBytes(Path.Combine(IOUtils.GetAppDataDir(), "av.7z"), Resources.av); dialog.ChangeText("Installing ESRGAN resources..."); await UnSevenzip(Path.Combine(IOUtils.GetAppDataDir(), "esrgan.7z")); dialog.ChangeText("Installing ESRGAN-NCNN-Vulkan resources..."); await UnSevenzip(Path.Combine(IOUtils.GetAppDataDir(), "ncnn.7z")); dialog.ChangeText("Installing Audio/Video/Image resources..."); await UnSevenzip(Path.Combine(IOUtils.GetAppDataDir(), "av.7z")); File.WriteAllText(Path.Combine(IOUtils.GetAppDataDir(), "shipped_files_version"), Resources.shipped_files_version); dialog.Close(); Program.mainForm.Enabled = true; Program.mainForm.WindowState = System.Windows.Forms.FormWindowState.Maximized; Program.mainForm.BringToFront(); }
/// <summary> /// 关闭 /// </summary> private static void CloseAsyMessage() { //上传等待取消 if (dialogForm != null) { dialogForm.Close(); dialogForm.Dispose(); } }
async Task DragNDrop(string [] files) { Logger.Log("[MainUI] Dropped " + files.Length + " file(s), files[0] = " + files[0]); IOUtils.ClearDir(Paths.tempImgPath.GetParentDir()); string path = files[0]; DialogForm loadingDialogForm = null; if (IOUtils.IsPathDirectory(path)) { htTabControl.SelectedIndex = 1; int compatFilesAmount = IOUtils.GetAmountOfCompatibleFiles(path, true); batchDirLabel.Text = "Loaded " + path.Wrap() + " - Found " + compatFilesAmount + " compatible files."; BatchUpscaleUI.LoadDir(path); upscaleBtn.Text = "Upscale " + compatFilesAmount + " Images"; return; } if (files.Length > 1) { htTabControl.SelectedIndex = 1; int compatFilesAmount = IOUtils.GetAmountOfCompatibleFiles(files); BatchUpscaleUI.LoadImages(files); batchDirLabel.Text = "Loaded " + compatFilesAmount + " compatible files."; upscaleBtn.Text = "Upscale " + compatFilesAmount + " Images"; return; } upscaleBtn.Text = "Upscale And Save"; htTabControl.SelectedIndex = 0; previewImg.Text = ""; SetProgress(0f, "Loading image..."); loadingDialogForm = new DialogForm("Loading " + Path.GetFileName(path) + "..."); await Task.Delay(20); MainUIHelper.ResetCachedImages(); if (!MainUIHelper.DroppedImageIsValid(path)) { SetProgress(0f, "Ready."); await Task.Delay(1); Program.CloseTempForms(); return; } Program.lastFilename = path; ReloadImage(false); if (failed) { FailReset(); return; } SetHasPreview(false); loadingDialogForm.Close(); SetRefreshPreviewBtns(true); SetProgress(0f, "Ready."); }
static async Task CreateVideo() { if (IOUtils.GetAmountOfFiles(Paths.framesOutPath, false) < 1) { return; } if (outputFormatBox.Text == Upscale.VidExportMode.MP4.ToStringTitleCase()) { outputFormat = Upscale.VidExportMode.MP4; } if (outputFormatBox.Text == Upscale.VidExportMode.GIF.ToStringTitleCase()) { outputFormat = Upscale.VidExportMode.GIF; } if (outputFormatBox.Text == Upscale.VidExportMode.SameAsSource.ToStringTitleCase()) { outputFormat = (Upscale.VidExportMode)Enum.Parse(typeof(Upscale.VidExportMode), Path.GetExtension(currentInPath).Replace(".", "").ToUpper()); } if (outputFormat == Upscale.VidExportMode.MP4) { DialogForm f = new DialogForm("Creating video from frames...", 300); await Task.Delay(10); await FFmpegCommands.FramesToMp4(Paths.framesOutPath, Config.GetBool("h265"), Config.GetInt("crf"), fps, "", false); if (Config.GetBool("vidEnableAudio")) { await FFmpegCommands.MergeAudio(Paths.framesOutPath + ".mp4", currentInPath); } f.Close(); } if (outputFormat == Upscale.VidExportMode.GIF) { DialogForm f = new DialogForm("Creating GIF from frames...\nThis can take a while for high-resolution GIFs.", 600); await Task.Delay(10); string outpath = Path.Combine(Paths.GetDataPath(), "frames-out.mp4").Wrap(); await FFmpeg.RunGifski($" -r {fps.RoundToInt()} -W 4096 -Q {Config.GetInt("gifskiQ")} -q -o {outpath} \"{Paths.framesOutPath}/\"*.\"png\""); f.Close(); } }
private async void saveMergedPreviewBtn_Click(object sender, EventArgs e) { DialogForm loadingForm = new DialogForm("Post-Processing And Saving..."); await Task.Delay(50); Upscale.currentMode = Upscale.UpscaleMode.Single; string ext = Path.GetExtension(Program.lastFilename); string outPath = Path.ChangeExtension(Program.lastFilename, null) + "[temp]" + ext + ".tmp"; previewImg.Image.Save(outPath); await Upscale.PostprocessingSingle(outPath, true); string outFilename = Upscale.FilenamePostprocess(MainUIHelper.lastOutfile); string finalPath = IOUtils.ReplaceInFilename(outFilename, "[temp]", ""); loadingForm.Close(); Program.ShowMessage("Saved to " + finalPath + ".", "Message"); }
public static async Task Install() { Program.mainForm.Enabled = false; DialogForm dialog = new DialogForm("Installing resources...\nThis only needs to be done once."); await Task.Delay(20); if (IOUtils.GetDirSize(path) > 0) { Logger.Log("[Installer] {path} is not 0 bytes - removing everything there to ensure a clean install."); dialog.ChangeText("Uninstalling older files..."); await Task.Delay(20); Uninstall(false); } Directory.CreateDirectory(path); path7za = Path.Combine(path, "7za.exe"); File.WriteAllBytes(path7za, Resources.x64_7za); try { await DownloadAndInstall(exeFilesVersion, "esrgan.7z"); await DownloadAndInstall(exeFilesVersion, "esrgan-ncnn.7z"); await DownloadAndInstall(exeFilesVersion, "av.7z"); await DownloadAndInstall(exeFilesVersion, "shipped-files-version.txt", false); } catch (Exception e) { MsgBox msg = Logger.ErrorMessage("Web Installer failed to run!\n", e); while (DialogQueue.IsOpen(msg)) { await Task.Delay(50); } Environment.Exit(1); return; } dialog.Close(); Program.mainForm.Enabled = true; Program.mainForm.WindowState = System.Windows.Forms.FormWindowState.Maximized; Program.mainForm.BringToFront(); }
public static async Task ConvertNcnnModel(string modelPath) { try { string modelName = Path.GetFileName(modelPath); ncnnDir = Path.Combine(Config.Get("modelPath"), ".ncnn"); Directory.CreateDirectory(ncnnDir); string outPath = Path.Combine(ncnnDir, Path.ChangeExtension(modelName, null)); Logger.Log("Checking for NCNN model: " + outPath); if (IOUtils.GetAmountOfFiles(outPath, false) < 2) { Logger.Log("Running model converter..."); DialogForm dialog = new DialogForm("Converting ESRGAN model to NCNN format..."); await RunConverter(modelPath); if (lastNcnnOutput.Contains("Error:")) { throw new Exception(lastNcnnOutput.SplitIntoLines().Where(x => x.Contains("Error:")).First()); } string moveFrom = Path.Combine(Paths.esrganPath, Path.ChangeExtension(modelName, null)); Logger.Log("Moving " + moveFrom + " to " + outPath); await IOUtils.CopyDir(moveFrom, outPath, "*", true); Directory.Delete(moveFrom, true); dialog.Close(); } else { Logger.Log("NCNN Model is cached - Skipping conversion."); } ESRGAN.currentNcnnModel = outPath; } catch (Exception e) { Logger.ErrorMessage("Failed to convert Pytorch model to NCNN format! It might be incompatible.", e); } }
public static async void BeforeAfterAnim(bool save, bool h264) { string ext = "gif"; if (h264) { ext = "mp4"; } DialogForm dialogForm = new DialogForm("Creating comparison " + ext.ToUpper() + "..."); string tempPath = Path.Combine(IOUtils.GetAppDataDir(), "giftemp"); string framesPath = Path.Combine(tempPath, "frames"); IOUtils.ClearDir(tempPath); Directory.CreateDirectory(framesPath); resultPreview = (Bitmap)ImgUtils.GetImage(Directory.GetFiles(IO.Paths.previewOutPath, "*.png.*", SearchOption.AllDirectories)[0]); Image image1 = originalPreview; Image image2 = resultPreview; if (Config.GetInt("comparisonUseScaling") == 1) { image1 = (Bitmap)ImgUtils.GetImage(Path.Combine(IO.Paths.previewPath, "preview.png.png")); } float scale = (float)image2.Width / (float)image1.Width; Logger.Log("Scale for animation: " + scale); string outpath = Path.Combine(tempPath, "comparison." + ext); if (image2.Width <= 2048 && image2.Height <= 2048) { image1.Scale(scale, InterpolationMode.NearestNeighbor).Save(Path.Combine(framesPath, "0.png")); image2.Save(Path.Combine(framesPath, "1.png")); if (h264) { await FFmpegCommands.FramesToOneFpsMp4(framesPath, false, 14, 9, "", false); File.Move(Path.Combine(tempPath, "frames." + ext), outpath); } else { await FFmpeg.RunGifski(" -r 1 -W 2048 -q -o " + outpath.Wrap() + " \"" + framesPath + "/\"*.\"png\""); } if (save) { string comparisonSavePath = Path.ChangeExtension(Program.lastFilename, null) + "-comparison." + ext; File.Copy(outpath, comparisonSavePath, true); dialogForm.Close(); Program.ShowMessage("Saved current comparison to:\n\n" + comparisonSavePath, "Message"); } else { StringCollection paths = new StringCollection(); paths.Add(outpath); Clipboard.SetFileDropList(paths); dialogForm.Close(); Program.ShowMessage("The " + ext.ToUpper() + " file has been copied. You can paste it into any folder.\n" + "Please note that pasting it into Discord or other programs won't work as the clipboard can't hold animated images.", "Message"); } } else { Program.ShowMessage("The preview is too large for making an animation. Please create a smaller cutout or choose a different comparison type.", "Error"); } dialogForm.Close(); }