Command Infrastructure and Public Commands
Command specifications, parser construction helpers, command input handling, and top-level command modules.
Command Package
Command Definitions for the GONet Wizard CLI and GUI
This package is the declarative registry for all user-invoked entry points in GONet Wizard, supporting both traditional command-line execution and GUI-backed workflows (PyWebview + a unified local UI server).
Each command is implemented in a dedicated module (e.g. show,
show_meta, run_dashboard) and exposes a
COMMAND object of type CommandSpec
describing its CLI signature. At runtime, the parser infrastructure wires these
specs into an argparse.ArgumentParser tree and dispatches to a handler.
Beyond the CLI, commands can optionally return structured UI results (preview publishes, window-open requests, or both). This enables a single command implementation to work in:
terminal-only mode (print/side effects only), and/or
GUI mode (open windows and publish HTML previews via the unified UI server)
Infrastructure Overview
The command system is split into focused modules that together provide a declarative, extensible command tree with optional UI presentation:
GONet_Wizard.commands.specsDefines the declarative modelsCommandSpecandParserSpec.GONet_Wizard.commands.inputsProvides CLI input normalization utilities such asExpandFilenames,expand_inputs(), andfilter_by_ext().GONet_Wizard.commands.parser_builderConstructs the full parser hierarchy fromPARSERand command specs viabuild_subparser().GONet_Wizard.commands.ui_bridgeDefines the UI result protocol (PublishRequest,WindowRequest) and wrappers that normalize and realize handler return values, enabling commands to publish previews and request managed windows.GONet_Wizard.commands.cli_coreA compatibility shim that re-exports the public API from the modules above to avoid churn in legacy imports.
Declarative Command Tree
This package declares the root PARSER object (a
ParserSpec) describing the top-level CLI
group. The centralized parser builder consumes PARSER to build the
complete command hierarchy dynamically.
Top-level commands are collected in COMMANDS. Experimental nested
command groups can be parked in the source tree without being registered in
PARSER; for example, the remote-camera connect workflow is currently
deferred and intentionally omitted from the public command tree.
Available Commands
GONet_Wizard.commands.showVisualize one or more GONet files and channels using Plotly.
GONet_Wizard.commands.show_metaExtract and display GONet file metadata as text or HTML.
GONet_Wizard.commands.extractExtract pixel counts from GONet files using configurable ROI shapes.
GONet_Wizard.commands.run_dashboardLaunch the interactive Dash-based GONet Wizard dashboard in a managed window.
GONet_Wizard.commands.build_full_arrayBuild or process full-array products from GONet inputs.
GONet_Wizard.commands.split_rawConvert RAW GONet JPEG files into standard TIFF and JPEG images.
GONet_Wizard.commands.guiLaunch the unified GUI launcher window.
Constants
COMMANDStupleTuple of top-level command modules registered under the root parser.
PARSERParserSpecRoot parser specification defining the command hierarchy for the CLI/GUI.
Specifications
Declarative CLI Specification Models
This module defines lightweight dataclass models used to describe the structure
of the GONet Wizard command-line interface in a declarative way. These
specifications are consumed by parser-construction utilities to build an
argparse.ArgumentParser tree without duplicating argument wiring logic
across command modules.
Classes
ParserSpecSpecification for a command group / subparser group (including nested groups).
CommandSpecSpecification for a single CLI command and its argument definitions.
- class GONet_Wizard.commands.specs.ParserSpec(dest, help, args)[source]
Bases:
objectDeclarative specification for an
argparsesubparser group.A
ParserSpecdescribes a command group (e.g., top-level commands or a nested group) by defining the destination name under whichargparsestores the selected command, a help string, and a configuration dictionary describing available commands and nested parser groups.
- class GONet_Wizard.commands.specs.CommandSpec(name, help, args)[source]
Bases:
objectDeclarative specification for a single CLI command.
A
CommandSpecdefines a command name, its help text, and a sequence of argument specifications that are passed through toargparse.ArgumentParser.add_argument()during parser construction.Command modules typically expose a
COMMANDinstance of this class and acli_handler(args)function. Parser builders may attach the handler viaset_defaults(handler=...)to enable dispatch after argument parsing.- args
A list of
argparse.ArgumentParser.add_argument()specification dictionaries.
Parser Construction
CLI Parser Construction Utilities
This module provides helper functions to build an argparse command tree
from declarative command and parser specifications. It supports both simple
leaf commands (no nested subcommands) and hierarchical command groups via
recursive subparser construction.
The resulting parsers are configured to dispatch to command handlers, with
handlers wrapped through wrap_handler_for_ui()
to enable consistent execution from both CLI and UI entry points.
Functions
register_simple_subcommand()Register a single leaf command specification on a subparser group.
build_subparser()Recursively construct a parser and its nested subparsers from a package-defined
PARSERspecification.
- GONet_Wizard.commands.parser_builder.register_simple_subcommand(subparsers, cmd)[source]
Register a single simple command (no nested subparsers) to a subparser group.
This function reads the
COMMANDspecification fromcmdto create a corresponding subparser, add its arguments, and attach a handler when the command exposes acli_handlerattribute.- Parameters:
subparsers (
argparse._SubParsersAction) – The subparser group to which the command parser will be added.cmd (
object) – A command module or object exposing aCOMMANDspecification and optionally acli_handlercallable.
- Return type:
- Returns:
None
- Raises:
KeyError – If an argument specification declares
"flags"but does not provide a valid sequence of flag strings.AttributeError – If
cmddoes not provide aCOMMANDattribute.
- GONet_Wizard.commands.parser_builder.build_subparser(parser, package)[source]
Recursively build subparsers from a package defining a
PARSERobject.This function attaches a subparser group to
parserusing the destination and help text defined bypackage.PARSER. It then registers any leaf commands listed underpackage.PARSER.args["commands"]and recursively constructs nested subcommand groups frompackage.PARSER.args["subparsers"].The subparser group is created with
parser_class=parser.__class__so that all generated subparsers inherit the same parser type as the parent. This is required when the root parser is a custom subclass (e.g.,SmartArgumentParser) and parse errors must be handled consistently across the entire command tree. Without this override, argparse would instantiate subparsers as plainargparse.ArgumentParserinstances, bypassing custom error/exit behavior implemented by the parent parser class.- Parameters:
parser (
argparse.ArgumentParser) – The parser to augment with subparsers.package (
object) – A package-like object exposing aPARSERspecification describing available commands and nested parser groups.
- Return type:
- Returns:
argparse.ArgumentParser– The updated parser instance.- Raises:
AttributeError – If
packagedoes not define aPARSERattribute.KeyError – If a nested subparser specification references a
parser_namethat is not present in the current subparser group’schoices.
Smart Parser
Smart argparse Wrapper for Classified Parse Errors
This module defines a custom argparse.ArgumentParser subclass that
replaces argparse’s default SystemExit-based error handling with structured,
typed exceptions.
The parser classifies parse failures into broad categories (e.g. missing
required arguments vs. unknown arguments) and preserves contextual information
such as the original argv and the inferred command token sequence. This
enables higher-level CLI logic to decide how to handle parse failures, including
routing specific cases to GUI-backed workflows.
Constants
_CURRENT_ARGVProcess-local copy of the current argument vector, used as a fallback for subparsers that are not explicitly initialized with an
argvreference.
Functions
set_current_argv()Store the current argument vector for later retrieval during parse errors.
_guess_cmd_tokens()Extract a best-effort command token sequence from an argument vector.
Classes
SmartArgumentParserSubclass of
argparse.ArgumentParserthat raisesCliParseErrorinstead of exiting the process.
- GONet_Wizard.commands.smart_parser.set_current_argv(argv)[source]
Store the current argument vector for parse-time error handling.
This function records a process-local copy of
argvso that subparsers created by argparse (which do not receive custom constructor arguments) can still access the full invocation context when reporting parse errors.
- GONet_Wizard.commands.smart_parser.normalize_negative_option_values(parser, argv)[source]
Normalize negative numeric option values before argparse sees them.
argparseaccepts negative numeric values for options in many simple cases, but values containing punctuation, such as-90,180, can be mistaken for an option token. Rewriting--angles -90,180as--angles=-90,180removes the ambiguity while preserving the user’s intended value.
- class GONet_Wizard.commands.smart_parser.SmartArgumentParser(*args, argv=None, **kwargs)[source]
Bases:
ArgumentParserArgument parser that raises structured exceptions on parse failure.
This class overrides argparse’s default error and exit behavior to raise
CliParseErrorinstead of callingsys.exit. Each error is classified into aParseErrorKindand includes contextual information about the original invocation.- _argv
Argument vector explicitly associated with this parser instance, if provided at construction time.
- parse_args(args=None, namespace=None)[source]
Parse arguments after normalizing ambiguous negative option values.
This preserves standard argparse behavior while allowing invocations such as
--angles -90,90to work as users expect.
- error(message)[source]
Handle an argparse parsing error.
This method classifies the failure based on the error message and raises a
CliParseErrorcontaining the classification and contextual information.- Parameters:
message (
str) – Error message produced by argparse.- Return type:
- Returns:
None
- Raises:
CliParseError – Always raised to signal a classified parse failure.
- exit(status=0, message=None)[source]
Intercept argparse exit calls.
This override ensures that any attempt by argparse to terminate the process results in a
CliParseErrorinstead.- Parameters:
- Return type:
- Returns:
None
- Raises:
CliParseError – Always raised to prevent process termination.
Argparse Errors
CLI Parse Error Models
This module defines small, typed models used to represent argument-parsing failures without terminating the process.
The primary consumer is the CLI entry point, which can catch these exceptions and choose between standard terminal error output and UI routing behavior.
Classes
ParseErrorKindEnumeration describing broad categories of parse failures.
CliParseErrorException carrying a classified parse failure along with context such as the argv that triggered it and the best-effort extracted command token sequence.
- class GONet_Wizard.commands.argparse_errors.ParseErrorKind(value)[source]
-
Classification categories for CLI parsing failures.
- MISSING_REQUIRED
A required argument was not provided (e.g., missing required positional).
- Type:
- exception GONet_Wizard.commands.argparse_errors.CliParseError(kind, message, argv=None, cmd_tokens=None)[source]
Bases:
ExceptionException raised to report a classified CLI parsing failure.
This exception is intended to replace argparse’s default
SystemExit-based error handling so callers can decide how to present failures (e.g., printing usage to stderr or opening a GUI form page).- kind
Classification of the parsing failure.
- Type:
CLI Core
Command-Line Interface Core Compatibility Layer
This module serves as a compatibility shim for the GONet Wizard command-line infrastructure. Historically, it hosted CLI specifications, input expansion helpers, parser construction utilities, and UI preview integration in a single location.
As the CLI architecture evolved, these responsibilities were split into dedicated modules to improve separation of concerns and maintainability:
This module re-exports the public API from those modules to preserve backward compatibility and avoid widespread changes to existing imports.
Constants
None
Classes
ParserSpecDeclarative specification for CLI parser groups.
CommandSpecDeclarative specification for individual CLI commands.
ExpandFilenamesargparse.Actionfor expanding CLI file inputs.ExtensionFilterErrorException raised when extension-based filtering yields no files.
PublishRequestRequest to publish HTML preview content.
WindowRequestRequest to open or focus a UI window.
Functions
expand_inputs()Expand CLI file tokens into concrete filesystem paths.
filter_by_ext()Filter file paths by allowed extensions.
maybe_present_ui_result()Realize UI results and start the webview loop if needed.
realize_ui_result()Normalize and apply UI result(s).
wrap_handler_for_ui()Wrap a CLI handler to support UI result emission.
build_subparser()Recursively construct an argparse subparser tree.
register_simple_subcommand()Register a leaf command on a subparser group.
- class GONet_Wizard.commands.cli_core.ParserSpec(dest, help, args)[source]
Bases:
objectDeclarative specification for an
argparsesubparser group.A
ParserSpecdescribes a command group (e.g., top-level commands or a nested group) by defining the destination name under whichargparsestores the selected command, a help string, and a configuration dictionary describing available commands and nested parser groups.
- class GONet_Wizard.commands.cli_core.CommandSpec(name, help, args)[source]
Bases:
objectDeclarative specification for a single CLI command.
A
CommandSpecdefines a command name, its help text, and a sequence of argument specifications that are passed through toargparse.ArgumentParser.add_argument()during parser construction.Command modules typically expose a
COMMANDinstance of this class and acli_handler(args)function. Parser builders may attach the handler viaset_defaults(handler=...)to enable dispatch after argument parsing.- args
A list of
argparse.ArgumentParser.add_argument()specification dictionaries.
- class GONet_Wizard.commands.cli_core.ExpandFilenames(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]
Bases:
Actionargparse.Actionto expand CLI filename tokens into concrete paths.This action normalizes user-provided input arguments that may include:
individual file paths
directories (non-recursive expansion)
wildcard patterns (e.g.
*.tiff)comma-separated lists of the above
The resolved paths are stored on the destination attribute as a
listofpathlib.Path.- None
- exception GONet_Wizard.commands.cli_core.ExtensionFilterError[source]
Bases:
ValueErrorRaised when extension-based filtering returns no files.
This exception indicates that an extension allowlist was applied to a set of candidate paths but no paths matched.
Notes
This is a subclass of
ValueErrorto communicate invalid user input in CLI contexts.
- GONet_Wizard.commands.cli_core.expand_inputs(tokens)[source]
Expand input tokens into a flat list of file paths.
Tokens may refer to explicit files, directories (expanded non-recursively), glob patterns, or comma-separated lists of these. The returned list preserves first-seen order while removing duplicates.
- Parameters:
Input tokens that may include:
individual file paths
directories (non-recursive expansion)
wildcard patterns (e.g.
*.tiff)comma-separated lists of the above
- Return type:
- Returns:
listofpathlib.Path– A flat list of expanded file paths aspathlib.Pathobjects.- Raises:
FileNotFoundError – If any token (or comma-separated sub-token) does not match one or more existing files.
- GONet_Wizard.commands.cli_core.filter_by_ext(paths, exts)[source]
Filter a list of file paths by extension.
This function normalizes the provided extension allowlist (case-insensitive, with or without leading dots) and returns the subset of paths whose
pathlib.Path.suffixmatches.- Parameters:
paths (
listofpathlib.Path) – List of file paths to filter.exts (
listofstr) – List of allowed file extensions (with or without leading dot). Example:['.tiff', '.tif', '.json']
- Return type:
- Returns:
listofpathlib.Path– Filtered list of file paths that match the allowed extensions.- Raises:
.ExtensionFilterError – If no files match the allowed extensions.
- class GONet_Wizard.commands.cli_core.PublishRequest(channel, html, title=None)[source]
Bases:
objectRequest to publish HTML into the PreviewManager under a channel.
- class GONet_Wizard.commands.cli_core.WindowRequest(key, spec, publish=None)[source]
Bases:
objectRequest to open/focus a window under a stable key.
A window request may optionally include a
PublishRequest, allowing preview content to be published before the window is shown.- spec
Window specification (title/url/size).
- Type:
- publish
If provided, publish preview HTML before opening/focusing the window.
- Type:
PublishRequest, optional
- GONet_Wizard.commands.cli_core.maybe_present_ui_result(cmd_name, result, *, port=5050, debug_webview=False)[source]
Realize any UI result and start the webview loop if windows were requested.
- Parameters:
- Return type:
- Returns:
None
- Raises:
RuntimeError – If UI realization requires starting the unified UI server and startup fails.
- GONet_Wizard.commands.cli_core.realize_ui_result(cmd_name, result, *, port)[source]
Apply UI result(s) and return whether any window was requested.
This function normalizes a handler return value and then: - publishes preview HTML when requested - ensures windows exist (or are focused) when requested - starts the unified UI server only when needed for preview-backed windows
- Parameters:
- Return type:
- Returns:
bool–Trueif at least oneWindowRequestwas realized, otherwiseFalse.- Raises:
RuntimeError – If the unified UI server cannot be started when required.
- GONet_Wizard.commands.cli_core.wrap_handler_for_ui(cmd)[source]
Wrap a command handler so it can emit UI results from a CLI invocation.
The returned function calls
cmd.cli_handlerand then interprets its return value usingmaybe_present_ui_result(). This allows commands to return:None(no UI action)str(legacy HTML preview; channel =COMMAND.name)PublishRequest(publish only)WindowRequest(open/focus a window, optional publish)
- Parameters:
cmd (
object) – Command module or object exposing acli_handlercallable and optionally aCOMMANDspecification.- Returns:
collections.abc.Callable– A handler compatible withargparsedispatch that accepts anargparse.Namespaceand performs any requested UI actions.- Raises:
AttributeError – If
cmddoes not definecli_handler.
- GONet_Wizard.commands.cli_core.build_subparser(parser, package)[source]
Recursively build subparsers from a package defining a
PARSERobject.This function attaches a subparser group to
parserusing the destination and help text defined bypackage.PARSER. It then registers any leaf commands listed underpackage.PARSER.args["commands"]and recursively constructs nested subcommand groups frompackage.PARSER.args["subparsers"].The subparser group is created with
parser_class=parser.__class__so that all generated subparsers inherit the same parser type as the parent. This is required when the root parser is a custom subclass (e.g.,SmartArgumentParser) and parse errors must be handled consistently across the entire command tree. Without this override, argparse would instantiate subparsers as plainargparse.ArgumentParserinstances, bypassing custom error/exit behavior implemented by the parent parser class.- Parameters:
parser (
argparse.ArgumentParser) – The parser to augment with subparsers.package (
object) – A package-like object exposing aPARSERspecification describing available commands and nested parser groups.
- Return type:
- Returns:
argparse.ArgumentParser– The updated parser instance.- Raises:
AttributeError – If
packagedoes not define aPARSERattribute.KeyError – If a nested subparser specification references a
parser_namethat is not present in the current subparser group’schoices.
- GONet_Wizard.commands.cli_core.register_simple_subcommand(subparsers, cmd)[source]
Register a single simple command (no nested subparsers) to a subparser group.
This function reads the
COMMANDspecification fromcmdto create a corresponding subparser, add its arguments, and attach a handler when the command exposes acli_handlerattribute.- Parameters:
subparsers (
argparse._SubParsersAction) – The subparser group to which the command parser will be added.cmd (
object) – A command module or object exposing aCOMMANDspecification and optionally acli_handlercallable.
- Return type:
- Returns:
None
- Raises:
KeyError – If an argument specification declares
"flags"but does not provide a valid sequence of flag strings.AttributeError – If
cmddoes not provide aCOMMANDattribute.
Input Expansion
CLI Input Expansion and File Extension Filtering
This module provides reusable utilities for expanding command-line file inputs into concrete filesystem paths. It supports common CLI input patterns including single files, non-recursive directory expansion, glob patterns, and comma-separated token lists, while preserving input order and removing duplicates.
These helpers are used primarily by argparse-based commands to normalize
user input before downstream processing (e.g., reading GONet files or JSON outputs).
Classes
ExtensionFilterErrorException raised when extension-based filtering yields no results.
ExpandFilenamesargparse.Actionthat expands CLI tokens into a list ofpathlib.Pathobjects.
Functions
expand_inputs()Expand file and directory tokens into a flat, de-duplicated list of paths.
filter_by_ext()Filter a list of paths by allowed file extensions.
- exception GONet_Wizard.commands.inputs.ExtensionFilterError[source]
Bases:
ValueErrorRaised when extension-based filtering returns no files.
This exception indicates that an extension allowlist was applied to a set of candidate paths but no paths matched.
Notes
This is a subclass of
ValueErrorto communicate invalid user input in CLI contexts.
- class GONet_Wizard.commands.inputs.ExpandFilenames(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]
Bases:
Actionargparse.Actionto expand CLI filename tokens into concrete paths.This action normalizes user-provided input arguments that may include:
individual file paths
directories (non-recursive expansion)
wildcard patterns (e.g.
*.tiff)comma-separated lists of the above
The resolved paths are stored on the destination attribute as a
listofpathlib.Path.- None
- GONet_Wizard.commands.inputs.expand_inputs(tokens)[source]
Expand input tokens into a flat list of file paths.
Tokens may refer to explicit files, directories (expanded non-recursively), glob patterns, or comma-separated lists of these. The returned list preserves first-seen order while removing duplicates.
- Parameters:
Input tokens that may include:
individual file paths
directories (non-recursive expansion)
wildcard patterns (e.g.
*.tiff)comma-separated lists of the above
- Return type:
- Returns:
listofpathlib.Path– A flat list of expanded file paths aspathlib.Pathobjects.- Raises:
FileNotFoundError – If any token (or comma-separated sub-token) does not match one or more existing files.
- GONet_Wizard.commands.inputs.filter_by_ext(paths, exts)[source]
Filter a list of file paths by extension.
This function normalizes the provided extension allowlist (case-insensitive, with or without leading dots) and returns the subset of paths whose
pathlib.Path.suffixmatches.- Parameters:
paths (
listofpathlib.Path) – List of file paths to filter.exts (
listofstr) – List of allowed file extensions (with or without leading dot). Example:['.tiff', '.tif', '.json']
- Return type:
- Returns:
listofpathlib.Path– Filtered list of file paths that match the allowed extensions.- Raises:
.ExtensionFilterError – If no files match the allowed extensions.
UI Bridge
CLI-to-UI Result Bridging Utilities
This module defines a small result protocol that allows CLI command handlers to optionally request UI behavior (publishing HTML previews and opening/focusing windows) without hard-coupling command modules to UI implementation details.
Command handlers may return legacy HTML strings (backward compatible) or structured request objects. Results are normalized and then realized by publishing preview content to the unified UI server and/or ensuring a window exists via the window manager. If windows are requested, the webview event loop is started.
Classes
PublishRequestRequest to publish an HTML document into the preview manager under a channel.
WindowRequestRequest to open/focus a window under a stable key, optionally publishing preview HTML first.
Functions
realize_ui_result()Normalize and apply UI result(s), returning whether a window was requested.
maybe_present_ui_result()Apply UI result(s) and start the webview loop if needed.
wrap_handler_for_ui()Wrap a command
cli_handlerso it can return UI results and be handled consistently from the CLI.
- class GONet_Wizard.commands.ui_bridge.PublishRequest(channel, html, title=None)[source]
Bases:
objectRequest to publish HTML into the PreviewManager under a channel.
- class GONet_Wizard.commands.ui_bridge.WindowRequest(key, spec, publish=None)[source]
Bases:
objectRequest to open/focus a window under a stable key.
A window request may optionally include a
PublishRequest, allowing preview content to be published before the window is shown.- spec
Window specification (title/url/size).
- Type:
- publish
If provided, publish preview HTML before opening/focusing the window.
- Type:
PublishRequest, optional
- GONet_Wizard.commands.ui_bridge.realize_ui_result(cmd_name, result, *, port)[source]
Apply UI result(s) and return whether any window was requested.
This function normalizes a handler return value and then: - publishes preview HTML when requested - ensures windows exist (or are focused) when requested - starts the unified UI server only when needed for preview-backed windows
- Parameters:
- Return type:
- Returns:
bool–Trueif at least oneWindowRequestwas realized, otherwiseFalse.- Raises:
RuntimeError – If the unified UI server cannot be started when required.
- GONet_Wizard.commands.ui_bridge.maybe_present_ui_result(cmd_name, result, *, port=5050, debug_webview=False)[source]
Realize any UI result and start the webview loop if windows were requested.
- Parameters:
- Return type:
- Returns:
None
- Raises:
RuntimeError – If UI realization requires starting the unified UI server and startup fails.
- GONet_Wizard.commands.ui_bridge.wrap_handler_for_ui(cmd)[source]
Wrap a command handler so it can emit UI results from a CLI invocation.
The returned function calls
cmd.cli_handlerand then interprets its return value usingmaybe_present_ui_result(). This allows commands to return:None(no UI action)str(legacy HTML preview; channel =COMMAND.name)PublishRequest(publish only)WindowRequest(open/focus a window, optional publish)
- Parameters:
cmd (
object) – Command module or object exposing acli_handlercallable and optionally aCOMMANDspecification.- Returns:
collections.abc.Callable– A handler compatible withargparsedispatch that accepts anargparse.Namespaceand performs any requested UI actions.- Raises:
AttributeError – If
cmddoes not definecli_handler.
Build Full Array Command
CLI command for building full-array GONet products.
The build_full_array command converts one or more RAW GONet .jpg files
into full-array .npz products. It delegates the image-processing work to
GONet_Wizard.GONet_utils.src.gonet.analysis_utils.full_array.build_full_array()
and keeps this module focused on CLI concerns: input expansion, extension
filtering, output-name selection, logging configuration, and parsing optional
channel weights.
The command is primarily intended for scripted preprocessing before downstream analysis or visualization.
Constants
COMMANDDeclarative command specification used by the shared parser builder and GUI form generator.
Functions
parse_channel_weights()Convert the
--weightsCLI string into a channel-to-weight mapping.cli_handler()Execute the command after argparse has populated the namespace.
- GONet_Wizard.commands.build_full_array.parse_channel_weights(weights)[source]
Parse comma-separated channel weights from the CLI.
The
--weightsoption accepts strings such as"red=0.25,green1=0.5,green2=0.5,blue=0.25". This helper converts that text representation into the mapping expected bybuild_full_array().- Parameters:
weights (
str, optional) – Comma-separatedname=valuepairs. If None, no custom channel weights are applied. Empty entries are ignored.- Return type:
- Returns:
dictor None – Mapping from channel name to floating-point weight, or None when no weights were provided.- Raises:
ValueError – If an entry is missing the
=separator, has an empty channel name, or contains a value that cannot be converted tofloat.
- GONet_Wizard.commands.build_full_array.cli_handler(args)[source]
CLI handler for the build_full_array command.
The input argument is expanded using
expand_inputs(), and filtered to include only RAW.jpgfiles. For each input file, the full-array image is built usingbuild_full_array()with the specified parameters.If multiple input files are provided and an outfile is specified, the outfile is treated as a suffix to be appended to each output file name.
- Parameters:
args (
argparse.Namespace) – Parsed command-line arguments.- Return type:
- Returns:
None
Extract Command
GONet Pixel Extraction Command-Line Module
This module provides command-line utility functions to extract pixel counts from GONet image files. It supports different geometric selection shapes (e.g., circles, rectangles, annuli, and free-form shapes) for region-of-interest definition. The extraction can be triggered either through direct parameters or by launching an interactive GUI.
The module validates user-provided parameters for the selected shape and ensures that the extraction process is performed correctly. Results are saved to a JSON file, with automatic handling of file overwrites.
The command is declared via the COMMAND constant, which specifies the
argument structure used by the centralized parser builder. When invoked from the
CLI, the parser dispatches directly to cli_handler(), which translates the
parsed argparse.Namespace into a call to the reusable plotting function.
Constants
COMMAND:CommandSpecobject for the extract command.
Functions
validate_output_file()Validate the output file path and ensure it does not overwrite an existing file.
comma_separated_pair()Parse and validate a string representing two comma-separated integers.
extract_counts_from_GONet()Perform counts extraction from one or more GONet files, using shape parameters provided by the user or launching the extraction GUI.
- GONet_Wizard.commands.extract.validate_output_file(output, output_type)[source]
Validate the output file path and ensure it does not overwrite an existing file.
If the file already exists, an index is appended or incremented to create a unique filename.
- Parameters:
- Return type:
- Returns:
tuple of
str– A unique output file path and the output type.- Raises:
ValueError – If the output file path is invalid.
- GONet_Wizard.commands.extract.comma_separated_pair(value, name)[source]
Parse and validate a string containing two comma-separated integers.
This function splits the provided string by commas, converts both parts to integers, and verifies that exactly two integers are present.
- Parameters:
- Returns:
tuple of
int– A tuple containing the two parsed integers.- Raises:
ValueError – If the input cannot be parsed into exactly two integers.
- GONet_Wizard.commands.extract.parse_float_argument(value, name)[source]
Parse a numeric CLI argument and report the offending option name.
- Parameters:
- Returns:
float– Parsed floating-point value.- Raises:
ValueError – If
valuecannot be converted to a number.
- GONet_Wizard.commands.extract.extract_counts_from_GONet(files, red=False, green=False, blue=False, shape=None, center=None, radius=None, sides=None, inner_radius=None, outer_radius=None, angles=None, output=None, output_type=None)[source]
Extract pixel counts from one or more GONet image files.
Depending on the provided shape parameter, the function validates associated geometric arguments (e.g. center, radius, sides, …) and performs counts extraction from the specified regions. If no shape is given or shape is set to ‘free’, the interactive extraction GUI is launched.
- Parameters:
files (
strorlistofstr) – Path(s) to one or more GONet image files to process.red (
bool, optional) – If True, extract counts from the red channel. Defaults to False.green (
bool, optional) – If True, extract counts from the green channel. Defaults to False.blue (
bool, optional) – If True, extract counts from the blue channel. Defaults to False.shape (
str, optional) –Shape of the extraction region. Supported values:
”circle”: Requires center and radius.
”rectangle”: Requires center and sides.
”annulus”: Requires center, radius or inner_radius and outer_radius.
”free” or None: Launch the interactive extraction GUI.
center (
str, optional) – Center coordinates of the region, as “x,y” (pixels).radius (
float, optional) – Radius of the region (pixels) for “circle” or “annulus” shapes.sides (
str, optional) – Side lengths of the rectangle as “width,height” (pixels).inner_radius (
float, optional) – Inner radius (pixels) for the “annulus” shape. Either inner_radius or radius must be provided for annulus.outer_radius (
float, optional) – Outer radius (pixels) for the “annulus” shape.angles (
str, optional) – Start and end angles in degrees, as “start_angle,end_angle”. Defaults to “-180,180”.output (
str, optional) – Name of the output JSON file.output_type (
str, optional) – Type of the output file, either “json” or “csv”. Defaults to “json
- Return type:
- Returns:
str or None – Absolute path to the written output file, or
Nonewhen the extraction is cancelled before writing output.- Raises:
ValueError – If required parameters for the chosen shape are missing or invalid.
Notes
If none of red, green, or blue are True, all channels will be extracted by default.
- GONet_Wizard.commands.extract.cli_handler(args)[source]
Dispatch the extraction command from parsed CLI arguments.
When no explicit shape is supplied, or when the shape is
"interactive", this handler launches the Dash-based extraction GUI and returns aWindowRequestfor the shared UI runtime. Otherwise, it runs the non-interactive extraction workflow directly and writes JSON or CSV output throughextract_counts_from_GONet().- Parameters:
args (
argparse.Namespace) – Parsed command-line arguments produced fromCOMMAND.- Returns:
WindowRequestor None – A window request when launching the interactive extraction GUI. Returns None after a non-interactive extraction run.- Raises:
ExtensionFilterError – If the supplied filenames do not include any supported GONet image files.
Split RAW Command
CLI command for splitting RAW GONet JPEG files into standard images.
The split_raw command reads one or more original GONet RAW .jpg files
and writes standard image products next to each input by default:
a 16-bit TIFF file (
<stem>.tiff), anda standard 8-bit JPEG file (
<stem>.jpeg).
When an output directory is supplied, the command keeps products organized in
separate tiffs and jpegs subdirectories. TIFF products do not apply white
balance by default so their pixel values remain as faithful as possible to the
RAW data for scientific extraction. JPEG products keep white balance enabled by
default because they are usually intended for visual inspection.
The image loading and writing are delegated to
GONet_Wizard.GONet_utils.GONetFile, which already knows how to parse
GONet RAW JPEG files and export the processed RGB channels. This module keeps
the command-layer behavior focused on CLI/GUI arguments, path handling, and
safe overwrite checks.
Constants
COMMANDDeclarative command specification used by the shared parser builder and GUI form generator.
Functions
output_paths_for_raw()Resolve the TIFF and JPEG output paths for one input file.
split_raw_file()Convert a single RAW input file into the requested output products.
split_raw_files()Convert a sequence of RAW input files.
cli_handler()Execute the command after argparse has populated the namespace.
The SplitRawOutput helper is a small return container used internally by
the command implementation. The public API documentation focuses on the
command specification and conversion helpers because those are the stable
integration points.
- GONet_Wizard.commands.split_raw.output_paths_for_raw(input_file, outdir=None, output_format='both')[source]
Resolve standard TIFF/JPEG output paths for one RAW input file.
By default, outputs are written next to the input. TIFF outputs use
<stem>.tiffand JPEG outputs use<stem>.jpegso the generated JPEG does not overwrite the source RAW.jpgfile. Whenoutdiris supplied, TIFF outputs are written underoutdir/tiffsand JPEG outputs underoutdir/jpegs.- Parameters:
input_file (
strorpathlib.Path) – Source RAW GONet JPEG file.outdir (
strorpathlib.Path, optional) – Base directory in which outputs should be written. If omitted, the input file’s parent directory is used.output_format (
str, optional) – Which product(s) to create:"both"(default),"tiff", or"jpeg".
- Return type:
SplitRawOutput- Returns:
SplitRawOutput– Named tuple containing the source path and requested output paths.
- GONet_Wizard.commands.split_raw.split_raw_file(input_file, outdir=None, output_format='both', overwrite=False, tiff_white_balance=False, jpeg_white_balance=True)[source]
Convert one RAW GONet JPEG file into standard image products.
- Parameters:
input_file (
strorpathlib.Path) – Source RAW GONet JPEG file.outdir (
strorpathlib.Path, optional) – Base output directory. If omitted, outputs are written next to the input. If supplied, products are written undertiffsandjpegssubfolders.output_format (
str, optional) – Which product(s) to create:"both"(default),"tiff", or"jpeg".overwrite (
bool, optional) – If True, existing outputs may be replaced. Defaults to False.tiff_white_balance (
bool, optional) – Whether to apply metadata white-balance gains to TIFF outputs. Defaults to False so TIFF pixel counts remain close to the RAW data.jpeg_white_balance (
bool, optional) – Whether to apply metadata white-balance gains to JPEG outputs. Defaults to True for visually useful JPEG products.
- Return type:
SplitRawOutput- Returns:
SplitRawOutput– Paths written for this input file.
- GONet_Wizard.commands.split_raw.split_raw_files(input_files, outdir=None, output_format='both', overwrite=False, tiff_white_balance=False, jpeg_white_balance=True)[source]
Convert multiple RAW GONet JPEG files into standard image products.
- Parameters:
input_files (iterable of
strorpathlib.Path) – Source RAW GONet JPEG files.outdir (
strorpathlib.Path, optional) – Base output directory for all products. If omitted, each input’s parent directory is used. If supplied, products are written undertiffsandjpegssubfolders.output_format (
str, optional) – Which product(s) to create:"both"(default),"tiff", or"jpeg".overwrite (
bool, optional) – If True, existing outputs may be replaced. Defaults to False.tiff_white_balance (
bool, optional) – Whether to apply metadata white-balance gains to TIFF outputs. Defaults to False.jpeg_white_balance (
bool, optional) – Whether to apply metadata white-balance gains to JPEG outputs. Defaults to True.
- Return type:
list[SplitRawOutput]- Returns:
list of
SplitRawOutput– Paths written for each input file.
- GONet_Wizard.commands.split_raw.cli_handler(args)[source]
CLI handler for the
split_rawcommand.The handler prints a terminal-friendly summary and intentionally returns
None. Returning an HTML-like string would be interpreted by the shared CLI UI bridge as a preview request, which would open an unnecessary window for this terminal-only conversion command.- Parameters:
args (
argparse.Namespace) – Parsed command-line arguments produced fromCOMMAND.- Return type:
- Returns:
None – Feedback is emitted to stdout so both the terminal and GUI fake terminal receive the same summary.
- Raises:
ExtensionFilterError – If the supplied inputs do not include supported RAW JPEG files.
Show Metadata Command
GONet Metadata Display Command
This module implements the show_meta CLI command, which extracts and displays
metadata from one or more GONet image files. Output can be rendered either as
plain text (for terminal use) or as HTML suitable for display in GUI contexts.
The command is declared via the COMMAND specification and dispatched
through cli_handler(). Core formatting is handled by show_metadata(),
which returns a rendered string without printing so callers can decide how to
present the result.
Constants
COMMANDCommandSpecdefining theshow_metacommand.
Classes
_EmitBufferInternal line buffer that renders accumulated output as text or HTML.
Functions
show_metadata()Extract and format metadata for one or more GONet files as text or HTML.
cli_handler()CLI entry point for
show_meta._render_value_html()Render a Python value as HTML, recursively formatting containers.
_dict_to_table()Render a mapping as an HTML table.
_list_to_table()Render a list/sequence as inline HTML or a table, depending on content.
- GONet_Wizard.commands.show_meta.show_metadata(files, *, as_html=False, pprint_indent=4, pprint_width=100)[source]
Extract and format metadata for one or more GONet files.
This function performs no printing. It returns a rendered string (text or HTML) so that callers may choose to print it, display it in a UI, or write it to disk.
- Parameters:
files (
strorSequenceofstr) – A single file path or a sequence of file paths pointing to GONet files.as_html (
bool, optional) – IfTrue, return the output as HTML. Defaults toFalse.pprint_indent (
int, optional) – Indentation passed topprint.pformat(). Defaults to4.pprint_width (
int, optional) – Width passed topprint.pformat(). Defaults to100.
- Return type:
- Returns:
str– Rendered output as a string (text by default, HTML ifas_html=True).- Raises:
ValueError – If
filesis empty.
- GONet_Wizard.commands.show_meta.save_metadata_pdf(files, save_path)[source]
Save the metadata shown by
show_metato a PDF file.- Parameters:
- Return type:
- Returns:
str– Final path written to disk.- Raises:
RuntimeError – If the ReportLab PDF backend is unavailable or the PDF cannot be written.
- GONet_Wizard.commands.show_meta.cli_handler(args)[source]
CLI handler for the
show_metacommand.This handler filters the provided inputs to supported file types and calls
show_metadata(). If--htmlis set, it returns the rendered HTML string so a higher-level UI wrapper can capture it; otherwise it prints the text output to stdout.- Parameters:
args (
argparse.Namespace) – Parsed command-line arguments. Expected to providefilenamesand an optionalhtmlflag.- Return type:
- Returns:
stror None – Rendered HTML string if--htmlis set; otherwiseNoneafter printing text output.- Raises:
.ExtensionFilterError – If none of the provided paths match the supported extensions.
Dashboard Command
GONet Dashboard Launcher Command
This module defines the dashboard CLI command used to launch the interactive
GONet Wizard dashboard. The command prepares and validates input data paths,
starts (or reuses) a Dash server instance, and requests that the dashboard be
opened in a managed UI window.
Input paths may refer to directories or individual files and are expanded using shared CLI utilities. Only supported data formats are forwarded to the dashboard backend.
The command is declared via the COMMAND specification and dispatched
through cli_handler(), which returns a
WindowRequest for UI presentation.
Constants
COMMANDCommandSpecdefining thedashboardcommand and its CLI arguments.
Functions
cli_handler()CLI entry point that prepares inputs, starts the dashboard server, and opens the dashboard window.
- GONet_Wizard.commands.run_dashboard.cli_handler(args)[source]
CLI handler for launching the GONet dashboard.
This handler expands and normalizes input paths, filters supported data files, ensures that the dashboard server is running, and returns a
WindowRequestinstructing the UI layer to open the dashboard window.- Parameters:
args (
argparse.Namespace) – Parsed command-line arguments. Expected attributes includeinput,debug, andport.- Returns:
WindowRequest– A request to open the GONet Wizard Dashboard window.- Raises:
.ExtensionFilterError – If no input files match the supported extensions.
RuntimeError – If the dashboard server cannot be started.
GUI Command
GONet GUI Launcher Command
This module defines the gui CLI command, which launches the GONet Wizard
graphical user interface. When invoked, the command ensures that the unified
local UI server is running and opens the main launcher window using the
window-management infrastructure.
The command is declared via the COMMAND specification and dispatched
through cli_handler(), which returns a WindowRequest
to open the launcher window.
Constants
COMMANDCommandSpecdefining theguicommand.
Functions
cli_handler()CLI entry point that starts the UI server and opens the launcher window.
- GONet_Wizard.commands.gui.cli_handler(args)[source]
CLI handler for launching the GONet GUI.
This handler ensures that the unified UI server is running on the requested port and returns a
WindowRequestinstructing the UI layer to open the main launcher window.- Parameters:
args (
argparse.Namespace) – Parsed command-line arguments. Expected to provide aportattribute specifying the UI server port.- Return type:
- Returns:
WindowRequest– A request to open the GONet Launcher window.- Raises:
RuntimeError – If the unified UI server cannot be started.
Deferred Camera Commands
The remote-camera command modules are kept in the source tree as deferred, experimental functionality. They are documented separately so their status is clear and they do not get confused with the core image-processing workflow.
GONet Connect Command.
This module defines the experimental connect command specification.
The remote-camera workflow is currently deferred and intentionally not
registered in the public GONet Wizard command tree. The COMMAND
constant is kept so the SSH workflow can be revived later or split into a
separate remote-control package without rebuilding the command specification.
Constants
COMMAND:CommandSpecobject for the connect command.
Subcommands for the connect Command
This package contains the experimental remote-camera helpers originally planned
for a nested connect command. These helpers perform remote operations on a
GONet device over SSH, such as triggering imaging or terminating running
processes.
The remote-camera workflow is currently deferred and intentionally not
registered in the public GONet Wizard command tree. The PARSER object is
kept here so the workflow can be revived later or moved into a separate remote
control package without reconstructing the command specification from scratch.
Parser Specification
The PARSER defined here specifies the following:
dest="connect_subcommand"The argparse attribute where the chosen subcommand name will be stored.helpThe help text that would be shown if the experimentalconnectgroup were registered.args={"commands": COMMANDS}Registers thesnapandterminatecommand modules—each of which provides aCommandSpecand a CLI handler.
This declarative structure allows the CLI builder to recursively attach this
subpackage under the main connect command with no manual argparse wiring.
Remote Snapshot Command for GONet Devices
This module implements the experimental snap remote-camera helper. The
remote-camera workflow is currently deferred and is not registered in the
public GONet Wizard command tree. The helper can execute the gonet4.py
imaging script on a GONet device, upload configuration files, stream live
output, and download newly created images.
The command is declared via the COMMAND constant, a
CommandSpec describing the CLI argument
structure. When parsed by the centralized CLI builder, this command is wired to
cli_handler(), which adapts the parsed argparse.Namespace to the
core execution function take_snapshot().
The underlying operation uses the ssh_connect() decorator from
ssh_utils to automatically manage SSH connections, ensuring that each
command runs with a valid paramiko client and that the connection is safely
closed afterward.
Functions
list_remote_files(): Lists files in a remote directory.get_local_file_hash(): Computes a hash of a local file.get_remote_file_hash(): Retrieves the hash of a remote file.upload_if_different(): Uploads a file only if it differs from the remote version.run_remote_script_with_live_output(): Executes a command remotely with live output streaming.snap(): Main entry point to execute a snapshot and transfer resulting images.cli_handler(): CLI handler adapting parsed arguments to the core function.
- GONet_Wizard.commands.connect_commands.snap.list_remote_files(ssh, folder)[source]
List files in a remote folder using SSH.
- Parameters:
ssh (
paramiko.client.SSHClient) – An active SSH client connection to the remote GONet device.folder (
str) – Path to the remote folder to list.
- Return type:
- Returns:
set– A set of filenames found in the remote folder.
- GONet_Wizard.commands.connect_commands.snap.get_local_file_hash(filepath, algo='sha256')[source]
Compute the hash of a local file.
- GONet_Wizard.commands.connect_commands.snap.get_remote_file_hash(ssh, remote_path, algo='sha256')[source]
Compute the hash of a remote file using SSH.
- Parameters:
ssh (
paramiko.client.SSHClient) – An active SSH client connection.remote_path (
str) – Path to the remote file.algo (
str, optional) – Hashing algorithm (default is ‘sha256’).
- Return type:
- Returns:
strorNone– The remote file’s hash, or None if the file does not exist or cannot be read.
- GONet_Wizard.commands.connect_commands.snap.upload_if_different(ssh, local_path, remote_path)[source]
Upload a file only if it differs from the remote version.
- Parameters:
ssh (
paramiko.client.SSHClient) – SSH connection to the GONet device.local_path (
str) – Path to the local file.remote_path (
str) – Destination path on the remote device.
- Return type:
- Returns:
None
- GONet_Wizard.commands.connect_commands.snap.run_remote_script_with_live_output(ssh, command)[source]
Run a remote command and stream stdout in real time.
- Parameters:
ssh (
paramiko.client.SSHClient) – SSH connection to the GONet device.command (
str) – The command to run remotely.
- Return type:
- Returns:
None
- GONet_Wizard.commands.connect_commands.snap.take_snapshot(ssh, config_file_path=None)[source]
Run the GONet imaging script remotely and download new files.
This function: - Checks current files in the image folder - Optionally uploads a config file if provided - Executes gonet4.py on the remote device - Downloads any newly created image files to the local machine
- Parameters:
ssh (
paramiko.client.SSHClient) – SSH connection (automatically provided by the decorator).config_file_path (
str, optional) – Local path to a configuration file to be used with gonet4.py.
- Return type:
- Returns:
None
Notes
Files are downloaded to the folder defined by
LOCAL_OUTPUT_FOLDER.Requires appropriate environment variables as defined in
GONet_Wizard.commands.settings.GONetConfig.
- GONet_Wizard.commands.connect_commands.snap.cli_handler(args)[source]
CLI handler for the snap command.
- Parameters:
args (
argparse.Namespace) – Parsed command-line arguments.- Return type:
- Returns:
None
Remote Termination of Imaging Processes on a GONet Device
This module implements the terminate_imaging subcommand of the GONet Wizard
CLI, allowing users to remotely stop imaging activity on a GONet device. This
includes clearing scheduled tasks, killing active gonet4.py processes, and
resetting the device’s status directory.
The command is declared through the COMMAND constant, a
CommandSpec describing the subcommand’s
name and help text. When registered by the centralized parser builder, this
command dispatches to cli_handler(), which invokes the core remote
operation terminate_imaging().
SSH operations are handled by the ssh_connect() decorator from
ssh_utils, which automatically establishes and tears down an SSH connection,
ensuring safe and consistent remote execution.
Functions
terminate_imaging(): Terminate remote imaging activity and remove scheduling tasks.cli_handler(): CLI handler to terminate remote imaging.
- GONet_Wizard.commands.connect_commands.terminate.terminate_imaging(ssh)[source]
Terminate remote imaging activity and remove scheduling tasks.
This function connects via SSH to the remote GONet device and performs the following: - Clears the crontab (removing all scheduled tasks) - Kills any remaining gonet4.py processes - Deletes contents of /home/pi/Tools/Status/ - Creates a marker file to indicate imaging is terminated and disabled
- Parameters:
ssh (
paramiko.client.SSHClient) – An active SSH connection provided by theGONet_Wizard.commands.connect.ssh_connect()decorator.- Return type:
- Returns:
None
Notes
The ssh_connect decorator handles connection and disconnection.
If crontab removal or process termination fails, a warning is printed.
- GONet_Wizard.commands.connect_commands.terminate.cli_handler(args)[source]
CLI handler to terminate remote imaging.
- Parameters:
args (
argparse.Namespace) – Parsed command-line arguments containing the necessary parameters.- Return type:
- Returns:
None
SSH Connection Utilities for GONet Remote Access.
This module defines a decorator for safely managing SSH connections to a remote GONet device.
It abstracts away the connection lifecycle, allowing decorated functions to focus solely on
their task with an active paramiko.client.SSHClient instance.
Environment
Uses credentials from GONet_Wizard.settings.GONetConfig:
GONET_USERGONET_PASSWORD
Functions
ssh_connect(): Decorator for establishing an SSH connection before calling a remote operation.
- GONet_Wizard.commands.connect_commands.ssh_utils.ssh_connect(func)[source]
Decorator for establishing an SSH connection before calling a remote operation.
This decorator wraps a function that requires a live SSH connection. It manages: - Setting up the SSH client - Connecting to the given GONet device IP - Passing the connected SSH client to the decorated function - Automatically closing the connection afterward
- Parameters:
func (Callable[[paramiko.client.SSHClient, Any], Any]) – A function that expects a connected SSH client as its first argument.
- Return type:
- Returns:
Callable[[str, Any], Any] – A new function that takes the GONet device IP address and any additional arguments. The SSH connection is established using the environment-configured credentials.
- Raises:
Exception – If the SSH connection fails for any reason (auth, network, etc.), the exception is propagated.
Example
>>> @ssh_connect ... def list_home(ssh): ... _, stdout, _ = ssh.exec_command("ls ~") ... print(stdout.read().decode())
>>> list_home("192.168.1.101")