Repository navigation
Expand file tree
/
Copy pathScriptDescriptor.cs
More file actions
206 lines (186 loc) · 11.4 KB
/
Copy pathScriptDescriptor.cs
File metadata and controls
206 lines (186 loc) · 11.4 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
using System;
using System.Collections.Generic;
using System.IO;
namespace SharpTagManager
{
// A script.json descriptor lets a script declare how it should be launched instead of relying
// on the app's built-in "guess an interpreter from the file extension" behavior. Drop it next
// to (or instead of) a plain script file inside Extra Files/Scripts/, named anything ending in
// .json — the app scans that folder for .json files and treats each one as a descriptor (see
// AppResources.LoadScripts). Alternatively, drop (or git clone) a whole folder into
// Extra Files/Scripts/ containing a "SharpTagScript.json" — the folder's own name becomes the script's default name unless the
// descriptor sets its own "name".
//
// Minimal example (a bare Python script with no special environment needs):
// {
// "name": "My Tagger",
// "run": "python",
// "args": ["my_script.py"]
// }
//
// Full example, including a dedicated venv and user-configurable options:
// {
// "name": "Florence-2 Tagger",
// "run": "python",
// "args": ["florence2/florence2.py"],
// "venv": {
// "pythonVersion": "3.10",
// "requirements": "florence2/requirements.txt"
// },
// "workingDirectory": "florence2",
// "env": { "HF_HOME": "D:/models/huggingface" },
// "options": [
// {
// "arg": "--device",
// "label": "Device",
// "description": "Which device to run inference on.",
// "type": "enum",
// "values": ["auto", "cuda", "cpu"],
// "default": "auto"
// },
// {
// "arg": "--timeout",
// "label": "Idle timeout (seconds)",
// "type": "integer",
// "default": 600,
// "min": 0,
// "max": 3600
// }
// ]
// }
//
// IMPORTANT — mode flags your script must tolerate: the app appends one extra bare argument
// after everything below, so your script's own argument parser needs to accept (and ignore) it
// rather than error out on an unrecognized flag:
// -process — a real dispatch, processing an actual image/tags (RPC method "process").
// -startup — launched from the app's "Scripting" menu with no work yet (e.g. to pre-warm
// a slow-loading model). Not a reason to exit unless your script is a quick
// one-shot that has no reason to keep running without a request.
// With Python's argparse, absorb it like this:
// parser.add_argument("-process", action="store_true", help=argparse.SUPPRESS)
// parser.add_argument("-startup", action="store_true", help=argparse.SUPPRESS)
class ScriptDescriptor
{
// Display name shown in the app's script lists/menus. Optional — falls back to the
// descriptor's own filename (without ".json") if omitted.
public string name { get; set; }
// The executable to launch, e.g. "python", "node", or a custom .exe name.
// - If this looks like a relative path AND that file actually exists next to this .json
// file, it's resolved to an absolute path.
// - Otherwise it's passed through as a bare command name and resolved from PATH — this
// is the normal case for "python".
// Ignored (and replaced with the venv's own python.exe) when a "venv" block below is set
// and successfully prepared.
public string run { get; set; }
// Command-line arguments passed to "run", in order, before any user-configured "options"
// values and the mode flag (see the class comment above). Each entry:
// - If it doesn't start with "-" AND resolves to a file/folder that exists relative to
// this .json's own folder, it's expanded to an absolute path automatically — this is
// how you reference your actual script file, e.g. "args": ["my_script.py"].
// - Otherwise it's passed through literally (quoted only if it contains a space).
public string[] args { get; set; }
// User-configurable options shown in the app's "Script Options" dialog before running.
// Each becomes a CLI argument appended after "args" and before the mode flag. Optional —
// omit entirely if the script takes no configurable options.
public ScriptOptionDef[] options { get; set; }
// Optional. When present, the app creates/maintains a dedicated Python virtual environment
// for this script via uv (instead of just resolving "python" from PATH) — see
// Utility/ScriptVenvManager.cs for exactly what this does and when it re-runs. Omit this
// block entirely for a script that's happy running against whatever Python is already on
// the user's PATH.
public VenvDescriptor venv { get; set; }
// Working directory for the launched process. A relative path resolves against this
// .json's own folder; an absolute path is used as-is. If omitted, the process inherits the
// app's own working directory (not this script's folder) — set this if your script relies
// on relative paths from its own location rather than resolving its own file path itself.
public string workingDirectory { get; set; }
// Extra environment variables to set on the launched process, e.g. a cache directory or a
// toggle some dependency reads from the environment. These are added on top of (and
// override, if a key collides with) the normal environment the process would otherwise
// inherit — PATH and everything else stays present.
public Dictionary<string, string> env { get; set; }
public static ScriptDescriptor Load(string jsonPath)
{
string json = File.ReadAllText(jsonPath);
ScriptDescriptor desc = new JsonMapper().Deserialize<ScriptDescriptor>(json);
// "path-enum" options list files from "directory" to build their dropdown — resolve a
// relative one against this descriptor's own folder now, so it means "next to the
// script" regardless of the app's own working directory.
string baseDir = Path.GetDirectoryName(Path.GetFullPath(jsonPath));
if (desc.options != null)
foreach (ScriptOptionDef opt in desc.options)
if (string.Equals(opt.type, "path-enum", StringComparison.OrdinalIgnoreCase)
&& !string.IsNullOrEmpty(opt.directory) && !Path.IsPathRooted(opt.directory))
opt.directory = Path.GetFullPath(Path.Combine(baseDir, opt.directory));
return desc;
}
}
class VenvDescriptor
{
// Python version to request, e.g. "3.10" or "3.11" — passed straight to
// `uv venv --python <pythonVersion>`. uv downloads that exact interpreter itself if it
// isn't already available, so this doesn't depend on what Python (if any) is on the user's
// machine already.
public string pythonVersion { get; set; }
// Path to a requirements.txt for this script, relative to this .json's own folder (or an
// absolute path). The venv is created as a ".venv" folder next to this file, and
// "uv pip install -r <requirements>" is run automatically — but only re-run when this
// file's contents (or pythonVersion above) actually change since the last successful
// install, so it doesn't reinstall on every single launch.
//
// Deliberately leave out any dependency whose exact build depends on the end user's own
// hardware (e.g. a CUDA-specific PyTorch wheel) — requirements.txt has no way to express
// "pick the right one for this machine". Instead, have your script detect the hardware and
// install that one itself on first run.
public string requirements { get; set; }
}
class ScriptOptionDef
{
// The CLI flag this option is passed as, e.g. "--device". Also used as the dictionary key
// for persisting the user's chosen value between runs.
public string arg { get; set; }
// Display name shown as the row label in the Script Options dialog. Optional — falls back
// to "arg" if omitted.
public string label { get; set; }
// Tooltip / help text shown for this option in the dialog. Optional.
public string description { get; set; }
// One of: "bool" | "enum" | "path-enum" | "integer" | "float" | "string" | "multiline" |
// "file" | "folder".
// bool — checkbox. When true, only the bare flag is emitted (e.g. "--verbose"), with
// no value; when false, nothing is emitted at all.
// enum — dropdown offering "values" as suggestions, but still freely editable (not a
// strict allow-list) — useful when a script accepts values beyond the common
// presets you want to list.
// path-enum — dropdown listing the files found in "directory" (re-scanned live each time
// it's opened, so dropping in a new file picks it up without restarting the
// app), also freely editable like "enum". The stored value is just the file
// name; when building the command line it's combined with "directory" into a
// full path unless the value is already rooted (e.g. hand-typed). Use this
// for "pick one of these preset files, or point at your own" options.
// integer / float — numeric field, clamped to "min"/"max" if set.
// string — plain text field.
// multiline — plain text field + "..." button opening a multi-line text editor (embedded
// newlines are preserved and passed through to the script as one argument).
// file — text field + "..." button opening a file-picker dialog.
// folder — text field + "..." button opening a folder-picker dialog.
// Anything else (or omitted) is treated as "string".
public string type { get; set; }
// Suggested values for the dropdown when type is "enum", e.g. ["auto", "cuda", "cpu"].
// Ignored for every other type.
public string[] values { get; set; }
// Initial value shown before the user changes anything. Its JSON type should match "type"
// (bool/number/string). If omitted, the default is: false for bool, 0 / 0.0 for
// integer/float, "" for everything else.
public object @default { get; set; }
// Clamp range for "integer" / "float" options. Either or both may be omitted for an
// unbounded min/max. Ignored for every other type.
public double? min { get; set; }
public double? max { get; set; }
// For type "file": initial directory the file-picker dialog opens to. Ignored by "folder",
// which always opens to its own last-used location.
// For type "path-enum": the folder to list files from — required for that type. A relative
// path resolves against this descriptor's own folder (see ScriptDescriptor.Load), so
// "prompts" means "the prompts folder next to this .json file".
public string directory { get; set; }
}
}