CLI: --no_config_save, add ArgParseExtensions

This commit is contained in:
N00MKRAD
2024-08-23 09:58:30 +02:00
parent 46f1ec652a
commit e5d87d4d2d
5 changed files with 132 additions and 17 deletions

View File

@@ -0,0 +1,106 @@
using Flowframes.IO;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Flowframes.Extensions
{
public static class ArgParseExtensions
{
public class Options
{
public NDesk.Options.OptionSet OptionsSet { get; set; }
public string BasicUsage { get; set; } = "";
public string AdditionalHelpText { get; set; } = "";
public bool AddHelpArg { get; set; } = true;
public bool AlwaysPrintHelp { get; set; } = false;
public bool PrintLooseArgs { get; set; } = true;
}
public static void PrintHelp(this Options opts)
{
opts.OptionsSet.PrintHelp(opts.BasicUsage, opts.PrintLooseArgs);
}
public static void PrintHelp(this NDesk.Options.OptionSet opts, string basicUsage, bool printLooseArgs)
{
var lines = new List<string>();
var lengths = new List<int>();
foreach (var opt in opts)
{
var names = string.Join(", ", opt.GetNames().Select(s => s == opt.GetNames().First() ? $"-{s}" : $"--{s}"));
lengths.Add(names.Length);
}
string looseStr = "<Loose Arguments>";
var maxLen = Math.Max(lengths.Max(), looseStr.Length);
foreach (var opt in opts)
{
var names = opt.GetNames().Select(s => s == opt.GetNames().First() ? $"-{s}".Replace("-<>", looseStr) : $"--{s}").ToList();
if (names.Contains(looseStr) && !printLooseArgs) continue;
string desc = opt.Description.IsEmpty() ? "?" : opt.Description;
lines.Add($"{string.Join(", ", names).PadRight(maxLen)} : {desc}");
}
string prog = Path.GetFileNameWithoutExtension(Paths.GetExe());
Logger.Log($"Usage:\n{prog} {basicUsage}\n{string.Join("\n", lines)}\n");
}
public static void AddHelpArgIfNotPresent(this Options opts)
{
bool alreadyHasHelpArg = false;
foreach (var opt in opts.OptionsSet)
{
if (opt.Description.Lower() == "show help" || opt.GetNames().Contains("help") || opt.GetNames().Any(n => n == "h"))
{
alreadyHasHelpArg = true;
break;
}
}
if (!alreadyHasHelpArg)
{
opts.OptionsSet.Add("h|help", "Show help", v => opts.OptionsSet.PrintHelp(opts.BasicUsage, opts.PrintLooseArgs));
}
}
public static bool TryParseOptions(this Options opts, IEnumerable<string> args)
{
if (opts.AddHelpArg)
{
opts.AddHelpArgIfNotPresent();
}
return opts.OptionsSet.TryParseOptions(args, opts.AlwaysPrintHelp, opts.BasicUsage, opts.PrintLooseArgs);
}
public static bool TryParseOptions(this NDesk.Options.OptionSet opts, IEnumerable<string> args, bool alwaysPrintHelp = false, string basicUsage = "", bool printLooseArgs = true)
{
try
{
bool canParse = args.Where(a => a.Trim() != "/?").Any();
if (canParse)
{
opts.Parse(args);
}
if (alwaysPrintHelp || !canParse)
{
opts.PrintHelp(basicUsage, printLooseArgs);
}
return canParse;
}
catch (Exception ex)
{
Logger.Log($"Failed to parse options! {ex}", true);
return false;
}
}
}
}

View File

@@ -368,6 +368,7 @@
<Compile Include="Data\QueryInfo.cs" />
<Compile Include="Data\ResumeState.cs" />
<Compile Include="Data\SubtitleTrack.cs" />
<Compile Include="Extensions\ArgParseExtensions.cs" />
<Compile Include="Extensions\ProcessExtensions.cs" />
<Compile Include="Forms\BatchForm.cs">
<SubType>Form</SubType>

View File

@@ -2,7 +2,6 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
@@ -11,7 +10,8 @@ namespace Flowframes.IO
class Config
{
private static string configPath;
public static Dictionary<string, string> cachedValues = new Dictionary<string, string>();
public static Dictionary<string, string> CachedValues = new Dictionary<string, string>();
public static bool NoWrite = false;
public static void Init()
{
@@ -29,7 +29,7 @@ namespace Flowframes.IO
File.Delete(configPath);
await Task.Delay(100);
cachedValues.Clear();
CachedValues.Clear();
await Task.Delay(100);
if (settingsForm != null)
@@ -52,7 +52,7 @@ namespace Flowframes.IO
public static void Set(string str, string value)
{
Reload();
cachedValues[str] = value;
CachedValues[str] = value;
WriteConfig();
}
@@ -61,14 +61,17 @@ namespace Flowframes.IO
Reload();
foreach(KeyValuePair<string, string> entry in keyValuePairs)
cachedValues[entry.Key] = entry.Value;
CachedValues[entry.Key] = entry.Value;
WriteConfig();
}
private static void WriteConfig()
{
SortedDictionary<string, string> cachedValuesSorted = new SortedDictionary<string, string>(cachedValues);
if (NoWrite)
return;
SortedDictionary<string, string> cachedValuesSorted = new SortedDictionary<string, string>(CachedValues);
File.WriteAllText(configPath, JsonConvert.SerializeObject(cachedValuesSorted, Formatting.Indented));
}
@@ -85,7 +88,7 @@ namespace Flowframes.IO
foreach (KeyValuePair<string, string> entry in deserializedConfig)
newDict.Add(entry.Key, entry.Value);
cachedValues = newDict; // Use temp dict and only copy it back if no exception was thrown
CachedValues = newDict; // Use temp dict and only copy it back if no exception was thrown
}
catch (Exception e)
{
@@ -118,8 +121,8 @@ namespace Flowframes.IO
try
{
if (cachedValues.ContainsKey(keyStr))
return cachedValues[keyStr];
if (CachedValues.ContainsKey(keyStr))
return CachedValues[keyStr];
return WriteDefaultValIfExists(key.ToString(), type);
}
@@ -221,7 +224,7 @@ namespace Flowframes.IO
static void WriteIfDoesntExist (string key, string val)
{
if (cachedValues.ContainsKey(key.ToString()))
if (CachedValues.ContainsKey(key.ToString()))
return;
Set(key, val);

View File

@@ -1,4 +1,5 @@
using Flowframes.Data;
using Flowframes.Extensions;
using Flowframes.Forms.Main;
using Flowframes.IO;
using Flowframes.MiscUtils;
@@ -21,7 +22,6 @@ namespace Flowframes
{
static class Program
{
public static string[] fileArgs = new string[0];
public static string[] args = new string[0];
public static bool initialRun = true;
public static Form1 mainForm;
@@ -35,7 +35,9 @@ namespace Flowframes
public static class Cli
{
public static bool DisablePython = false;
public static bool ShowMdlDownloader = false;
public static bool DontSaveConfig = false;
public static bool ExitWhenDone = false;
public static bool InterpStart = false;
public static float InterpFactor = -1f;
@@ -69,11 +71,8 @@ namespace Flowframes
Config.Init();
Task.Run(() => DiskSpaceCheckLoop());
fileArgs = Environment.GetCommandLineArgs().Where(a => a[0] != '-' && File.Exists(a)).ToList().Skip(1).ToArray();
args = Environment.GetCommandLineArgs().Where(a => a[0] == '-').Select(x => x.Trim().Substring(1).ToLowerInvariant()).ToArray();
Logger.Log($"Command Line: {Environment.CommandLine}", true);
Logger.Log($"Files: {(fileArgs.Length > 0 ? string.Join(", ", fileArgs) : "None")}", true);
Logger.Log($"Args: {(args.Length > 0 ? string.Join(", ", args) : "None")}", true);
HandleCli();
LaunchGui();
@@ -86,8 +85,9 @@ namespace Flowframes
var opts = new OptionSet
{
{ "np|no_python", "Disable Python implementations", v => Python.DisablePython = v != null },
{ "np|no_python", "Disable Python implementations", v => Cli.DisablePython = v != null },
{ "md|open_model_downloader", "Open model downloader GUI on startup", v => Cli.ShowMdlDownloader = v != null },
{ "nc|no_config_save", "Do not save anything in config during this session", v => Cli.DontSaveConfig = v != null },
{ "e|exit", "Exit automatically after interpolation has finished", v => Cli.ExitWhenDone = v != null },
{ "s|start", "Start interpolation automatically if valid parameters are provided", v => Cli.InterpStart = v != null },
{ "f|factor=", "Interpolation factor", v => Cli.InterpFactor = v.GetFloat() },
@@ -100,10 +100,15 @@ namespace Flowframes
try
{
opts.Parse(Environment.GetCommandLineArgs());
if (!opts.TryParseOptions(Environment.GetCommandLineArgs()))
return;
Cli.ValidFiles = Cli.ValidFiles.Skip(1).Where(f => File.Exists(f)).ToList();
Logger.Log($"Parsed CLI: Start {Cli.InterpStart}, Exit {Cli.ExitWhenDone}, Factor {Cli.InterpFactor}, AI {Cli.InterpAi}, Model '{Cli.InterpModel}', " +
$"Video Format {Cli.OutputFormat}, Output Dir '{Cli.OutputDir}', No Python {Python.DisablePython}, MdlDl {Cli.ShowMdlDownloader}", true);
Python.DisablePython = Cli.DisablePython;
Config.NoWrite = Cli.DontSaveConfig;
}
catch (OptionException e)
{

View File

@@ -84,7 +84,7 @@ namespace Flowframes.Ui
grid.Rows.Clear();
foreach (KeyValuePair<string, string> keyValuePair in Config.cachedValues)
foreach (KeyValuePair<string, string> keyValuePair in Config.CachedValues)
{
grid.Rows.Add(keyValuePair.Key, keyValuePair.Value);
}