Beispiel #1
0
        public static async Task CopyImages(string[] imgs, int targetAmount = 0)
        {
            IOUtils.ClearDir(Paths.imgInPath);

            int i = 0;

            foreach (string img in imgs)
            {
                if (IOUtils.compatibleExtensions.Contains(Path.GetExtension(img).ToLower()) && File.Exists(img))
                {
                    File.Copy(img, Path.Combine(Paths.imgInPath, Path.GetFileName(img)));
                    i++;
                    float prog = -1f;
                    if (targetAmount > 0)
                    {
                        prog = ((float)i / targetAmount) * 100f;
                    }
                    if (i % 20 == 0)
                    {
                        Program.mainForm.SetProgress(prog, $"Copied {i} images...");
                    }
                }
                await Task.Delay(1);
            }
        }
Beispiel #2
0
 static void LoadVideo()
 {
     IOUtils.ClearDir(Paths.framesOutPath);
     fps = FFmpegCommands.GetFramerate(currentInPath);
     Print("Detected frame rate of video as " + fps);
     IOUtils.ClearDir(Paths.imgInPath);
 }
 public static void Start(string outpath)
 {
     Logger.Log("[Queue] Start()");
     currentOutPath = outpath;
     outputFileQueue.Clear();
     processedFiles.Clear();
     outputFiles.Clear();
     IOUtils.ClearDir(Paths.imgOutNcnnPath);
     run = true;
 }
Beispiel #4
0
        private async void runBtn_Click(object sender, EventArgs e)
        {
            if (PreviewUI.previewImg.Image == null || !File.Exists(Paths.tempImgPath))
            {
                Program.ShowMessage("No image loaded!", "Error");
                return;
            }
            Enabled    = false;
            cutoutMode = cropMode.SelectedIndex == 1;
            if (cutoutMode)
            {
                IOUtils.ClearDir(Paths.previewPath);
                PreviewUI.SaveCurrentCutout();
                currentSourcePath = Path.Combine(Paths.previewPath, "preview.png");
            }
            else
            {
                currentSourcePath = Paths.tempImgPath;
            }
            string[] lines = Regex.Split(modelPathsBox.Text, "\r\n|\r|\n");
            if (comparisonMode.SelectedIndex == 0)
            {
                string outpath = Path.Combine(Paths.imgOutPath, "!Original.png");
                await ImageProcessing.ConvertImage(currentSourcePath, GetSaveFormat(), false, ImageProcessing.ExtMode.UseNew, false, outpath);
                await ProcessImage(outpath, "Original");
            }
            for (int i = 0; i < lines.Length; i++)
            {
                if (!File.Exists(lines[i]))
                {
                    continue;
                }
                ModelData mdl = new ModelData(lines[i], null, ModelData.ModelMode.Single);
                await DoUpscale(i, mdl, !cutoutMode);
            }
            bool        vert       = compositionMode.SelectedIndex == 1;
            MagickImage merged     = ImgUtils.MergeImages(Directory.GetFiles(Paths.imgOutPath, "*.png", SearchOption.AllDirectories), vert, true);
            string      mergedPath = Path.Combine(Paths.imgOutPath, Path.GetFileNameWithoutExtension(Program.lastImgPath) + "-composition");

            mergedPath = Path.ChangeExtension(mergedPath, GetSaveExt());
            merged.Write(mergedPath);
            await Upscale.CopyImagesTo(Program.lastImgPath.GetParentDir());

            IOUtils.ClearDir(Paths.previewPath);
            Enabled = true;
            Program.ShowMessage("Saved model composition to " + Program.lastImgPath.GetParentDir() + "\\" + Path.GetFileName(mergedPath), "Message");
        }
Beispiel #5
0
        public static async Task CopyImagesTo(string path)
        {
            Program.lastOutputDir = path;
            Program.mainForm.AfterFirstUpscale();
            if (overwriteMode == Overwrite.Yes)
            {
                Logger.Log("Overwrite mode - removing suffix from filenames");
                IOUtils.ReplaceInFilenamesDir(Paths.imgOutPath, "-" + GetLastModelName(), "");
            }
            else
            {
                Logger.Log("Overwrite is off - keeping suffix.");
            }
            IOUtils.Copy(Paths.imgOutPath, path);
            await Task.Delay(1);

            IOUtils.ClearDir(Paths.imgInPath);
            IOUtils.ClearDir(Paths.imgOutPath);
        }
Beispiel #6
0
        public static async Task Run(bool preprocess)
        {
            logBox.Clear();
            Print("Starting upscale of " + Path.GetFileName(currentInPath));
            if (string.IsNullOrWhiteSpace(currentInPath) || !File.Exists(currentInPath))
            {
                Program.ShowMessage("No valid file loaded.", "Error");
                return;
            }
            if (!IOUtils.HasEnoughDiskSpace(IOUtils.GetAppDataDir(), 10.0f))
            {
                Program.ShowMessage($"Not enough disk space on {IOUtils.GetAppDataDir().Substring(0, 3)} to store temporary files!", "Error");
                return;
            }
            Program.mainForm.SetBusy(true);
            LoadVideo();
            Print("Extracting frames...");
            await FFmpegCommands.VideoToFrames(currentInPath, Paths.imgInPath, false, false, false);

            int amountFrames = IOUtils.GetAmountOfCompatibleFiles(Paths.imgInPath, false);

            Print($"Done - Extracted  {amountFrames} frames.");
            await PreprocessIfNeeded(preprocess);

            BatchUpscaleUI.LoadDir(Paths.imgInPath, true);
            Print("Upscaling frames...");
            await BatchUpscaleUI.Run(false, true, Paths.framesOutPath);

            RenameOutFiles();
            Print($"Done upscaling all frames.");
            BatchUpscaleUI.Reset();
            Print("Creating video from frames...");
            await CreateVideo();

            Print("Done creating video.");
            CopyBack(Path.Combine(IOUtils.GetAppDataDir(), "frames-out.mp4"));
            Print("Adding audio from source to output video...");
            IOUtils.ClearDir(Paths.imgInPath);
            IOUtils.ClearDir(Paths.framesOutPath);
            Program.mainForm.SetBusy(false);
            Print("Finished.");
        }
Beispiel #7
0
        async Task LoadImages(string [] files)
        {
            Logger.Log("[MainUI] Dropped " + files.Length + " file(s), files[0] = " + files[0]);
            IOUtils.ClearDir(Paths.tempImgPath.GetParentDir());
            string path = files[0];

            if (IOUtils.IsPathDirectory(path))
            {
                htTabControl.SelectedIndex = 1;
                BatchUpscaleUI.LoadDir(path);
                return;
            }
            if (files.Length > 1)
            {
                htTabControl.SelectedIndex = 1;
                BatchUpscaleUI.LoadImages(files);
                return;
            }
            upscaleBtn.Text            = "Upscale And Save";
            htTabControl.SelectedIndex = 0;
            previewImg.Text            = "";
            SetProgress(0f, "Loading image...");
            PreviewUI.ResetCachedImages();
            if (!PreviewUI.DroppedImageIsValid(path))
            {
                SetProgress(0f, "Ready.");
                await Task.Delay(1);

                Program.CloseTempForms();
                return;
            }
            Program.lastImgPath = path;
            ReloadImage(false);
            if (failed)
            {
                FailReset(); return;
            }
            SetHasPreview(false);
            ImageLoadedChanged(true);
            SetProgress(0f, "Ready.");
        }
Beispiel #8
0
        static async Task CopyCompatibleImagesToTemp(bool move = false)
        {
            IOUtils.ClearDir(Paths.imgOutPath);
            Logger.Log("currentInDir: " + currentInDir + ", imgInPath: " + Paths.imgInPath);

            if (currentInDir == Paths.imgInPath)    // Skip if we are directly upscaling the img-in folder
            {
                return;
            }

            Logger.Log($"Clearing '{Paths.imgInPath}'");
            IOUtils.ClearDir(Paths.imgInPath);

            if (multiImgMode)
            {
                await CopyImages(currentInFiles);
            }
            else
            {
                await IOUtils.CopyDir(currentInDir, Paths.imgInPath, "*", false, true);
            }
        }
Beispiel #9
0
        static async Task CopyCompatibleImagesToTemp(bool move = false)
        {
            IOUtils.ClearDir(Paths.imgOutPath);

            Logger.Log("currentInDir: " + currentInDir + ", imgInPath: " + Paths.imgInPath);
            if (currentInDir == Paths.imgInPath)    // Skip if we are directly upscaling the img-in folder
            {
                return;
            }

            Logger.Log("Clearing imgInPath");

            IOUtils.ClearDir(Paths.imgInPath);
            if (multiImgMode)
            {
                await CopyImages(currentInFiles);
            }
            else
            {
                string[] files = IOUtils.GetCompatibleFiles(currentInDir, true);
                await CopyImages(files, files.Length);
            }
        }
Beispiel #10
0
        static async Task Install()
        {
            Print("Done downloading!");
            Print("Extracting...");
            if (Directory.Exists(extractPath))
            {
                IOUtils.ClearDir(extractPath);
            }
            List <Task> tasks = new List <Task>();

            isExtracting = true;
            tasks.Add(CheckDownloadedFileSizeAsync());
            tasks.Add(ExtractAsync());
            await Task.WhenAll(tasks);

            Print("Done extracting files.");
            MsgBox msg = Program.ShowMessage("The Python files will now be compressed to reduce the amount of storage space needed " +
                                             "from 2.4 GB to 1.6 GB.\nThis can take a few minutes.", "Message");

            while (DialogQueue.IsOpen(msg))
            {
                await Task.Delay(50);
            }
            Print("Compressing files...");
            RunCompact();
            Print("Done!");
            Config.Set("pythonRuntime", "1");
            await Init();

            MsgBox msg2 = Program.ShowMessage("Installed embedded Python runtime and enabled it!\nIf you want to disable it, you can do so in the settings.", "Message");

            while (DialogQueue.IsOpen(msg2))
            {
                await Task.Delay(50);
            }
            runBtn.Enabled = true;
        }
Beispiel #11
0
        public static async Task UpscaleImage()
        {
            if (previewImg.Image == null)
            {
                Program.ShowMessage("Please load an image first!", "Error");
                return;
            }

            Program.mainForm.SetBusy(true);
            IOUtils.ClearDir(Paths.imgInPath);
            IOUtils.ClearDir(Paths.imgOutPath);
            Program.mainForm.SetProgress(3f, "Preprocessing...");
            string inImg = CopyImage();

            if (inImg == null)  // Try to copy/move image to input folder, return if failed
            {
                Cancel("I/O Error");
                return;
            }

            Upscale.currentMode = Upscale.UpscaleMode.Single;
            await ImageProcessing.PreProcessImage(inImg, !Config.GetBool("alpha"));

            ModelData mdl    = Upscale.GetModelData();
            string    outImg = null;

            sw.Restart();

            try
            {
                bool           useNcnn = (Config.Get("cudaFallback").GetInt() == 2 || Config.Get("cudaFallback").GetInt() == 3);
                bool           useCpu  = (Config.Get("cudaFallback").GetInt() == 1);
                ESRGAN.Backend backend = ESRGAN.Backend.CUDA;
                if (useCpu)
                {
                    backend = ESRGAN.Backend.CPU;
                }
                if (useNcnn)
                {
                    backend = ESRGAN.Backend.NCNN;
                }
                await ESRGAN.DoUpscale(Paths.imgInPath, Paths.imgOutPath, mdl, false, Config.GetBool("alpha"), ESRGAN.PreviewMode.None, backend);

                if (backend == ESRGAN.Backend.NCNN)
                {
                    outImg = Directory.GetFiles(Paths.imgOutPath, "*.png*", SearchOption.AllDirectories)[0];
                }
                else
                {
                    outImg = Directory.GetFiles(Paths.imgOutPath, "*.tmp", SearchOption.AllDirectories)[0];
                }
                Program.mainForm.SetProgress(100f, "Post-Processing...");
                await Task.Delay(50);

                await Upscale.PostprocessingSingle(outImg, false);

                string outFilename = Upscale.FilenamePostprocess(lastOutfile);
                await Upscale.CopyImagesTo(Path.GetDirectoryName(Program.lastImgPath));
            }
            catch (Exception e)
            {
                Program.mainForm.SetProgress(0f, "Cancelled.");
                if (Program.cancelled)
                {
                    return;
                }
                if (e.StackTrace.Contains("Index"))
                {
                    Program.ShowMessage("The upscale process seems to have exited before completion!", "Error");
                }
                Logger.ErrorMessage("An error occured during upscaling:", e);
            }

            if (!Program.cancelled)
            {
                Program.mainForm.SetProgress(0, $"Done - Upscaling took {(sw.ElapsedMilliseconds / 1000f).ToString("0.0")}s");
            }

            Program.mainForm.SetBusy(false);
        }
Beispiel #12
0
        public static async void UpscalePreview(bool fullImage = false)
        {
            if (!HasValidModelSelection())
            {
                Program.ShowMessage("Invalid model selection.\nMake sure you have selected a model and that the file still exists.", "Error");
                return;
            }
            if (Config.Get("cudaFallback").GetInt() == 3 && !Program.mainForm.HasValidNcnnModelSelection())
            {
                Program.ShowMessage("Invalid model selection - NCNN does not support interpolation or chaining.", "Error");
                return;
            }
            Upscale.currentMode = Upscale.UpscaleMode.Preview;
            Program.mainForm.SetBusy(true);
            Program.mainForm.SetProgress(2f, "Preparing...");
            Program.mainForm.resetState = new Cupscale.PreviewState(previewImg.Image, previewImg.Zoom, previewImg.AutoScrollPosition);
            await Task.Delay(20);

            ResetCachedImages();
            IOUtils.ClearDir(Paths.imgInPath);
            IOUtils.ClearDir(Paths.previewPath);
            IOUtils.ClearDir(Paths.previewOutPath);
            ESRGAN.PreviewMode prevMode = ESRGAN.PreviewMode.Cutout;
            if (fullImage)
            {
                prevMode = ESRGAN.PreviewMode.FullImage;
                if (!IOUtils.TryCopy(Paths.tempImgPath, Path.Combine(Paths.previewPath, "preview.png"), true))
                {
                    return;
                }
            }
            else
            {
                SaveCurrentCutout();
            }
            ClipboardComparison.originalPreview = (Bitmap)ImgUtils.GetImage(Directory.GetFiles(IO.Paths.previewPath, "*.png.*", SearchOption.AllDirectories)[0]);
            await ImageProcessing.PreProcessImages(Paths.previewPath, !bool.Parse(Config.Get("alpha")));

            string tilesize = Config.Get("tilesize");
            bool   alpha    = bool.Parse(Config.Get("alpha"));

            ESRGAN.Backend backend = ESRGAN.Backend.CUDA;
            if (Config.Get("cudaFallback").GetInt() == 1)
            {
                backend = ESRGAN.Backend.CPU;
            }
            if (Config.Get("cudaFallback").GetInt() == 3)
            {
                backend = ESRGAN.Backend.NCNN;
            }

            sw.Restart();

            if (currentMode == Mode.Single)
            {
                string mdl1 = Program.currentModel1;
                if (string.IsNullOrWhiteSpace(mdl1))
                {
                    return;
                }
                ModelData mdl = new ModelData(mdl1, null, ModelData.ModelMode.Single);
                await ESRGAN.DoUpscale(Paths.previewPath, Paths.previewOutPath, mdl, false, alpha, prevMode, backend);
            }
            if (currentMode == Mode.Interp)
            {
                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);
                await ESRGAN.DoUpscale(Paths.previewPath, Paths.previewOutPath, mdl, false, alpha, prevMode, backend);
            }
            if (currentMode == Mode.Chain)
            {
                string mdl1 = Program.currentModel1;
                string mdl2 = Program.currentModel2;
                if (string.IsNullOrWhiteSpace(mdl1) || string.IsNullOrWhiteSpace(mdl2))
                {
                    return;
                }
                ModelData mdl = new ModelData(mdl1, mdl2, ModelData.ModelMode.Chain);
                await ESRGAN.DoUpscale(Paths.previewPath, Paths.previewOutPath, mdl, false, alpha, prevMode, backend);
            }
            if (currentMode == Mode.Advanced)
            {
                ModelData mdl = new ModelData(null, null, ModelData.ModelMode.Advanced);
                await ESRGAN.DoUpscale(Paths.previewPath, Paths.previewOutPath, mdl, false, alpha, prevMode, backend);
            }
            if (!Program.cancelled)
            {
                Program.mainForm.SetProgress(0, $"Done - Upscaling took {(sw.ElapsedMilliseconds / 1000f).ToString("0.0")}s");
            }
            Program.mainForm.SetBusy(false);
        }