Sirilpy Python Module API 1.0.25 Reference

The sirilpy python module supports communication with a running Siril instance. It can request representations of the current loaded image plus its metadata, including details of detected stars, as well as the current loaded sequence and most frame metadata.

Cette documentation est généré automatique depuis la version 1.0.25 du module python.

It can also run Siril commands using the SirilInterface.cmd() method, and the intent is to provide a capable interface for writing advanced scripts for Siril to a level not possible with the previous simple script files.

For example, scripts can now have PyQt6 or TKinter front ends using the PyQt6 or tkinter and ttkthemes modules, and they can utilise a lot of the ecosystem of Python modules including numpy, scipy, pillow and many more.

Note

Il existe certaines restrictions concernant les modules qui nécessitent l'installation de paquets binaires système pour fonctionner.

In the initial module release, most methods relating to the image or sequence loaded in Siril are read-only. The intent is that the parameters of the loaded image or sequence can be obtained and used as inputs to scripts, for example for calculations or input to conditionals, but the existing mature Siril command set should in most cases be used to act on the loaded image. Thus header keywords can be set using cmd("update_key", "key", "value"), and most built-in image operations can be carried out using the appropriate Siril command. The main exception to the rule of python methods providing read-only access is the set_image_pixeldata() method, which allows for setting the pixel data in the loaded image from a numpy array. This means that new pixel processing algorithms can be added using python, initially getting the pixel data from the loaded image using get_image_pixeldata() and setting it on completion using set_image_pixeldata(). Similar functions are available for getting and setting pixel data from sequence frames.

Dépendances

The sirilpy module depends on the following:

  • numpy >= 1.20.0

  • packaging >= 21.0

  • pywin32 >= 300 (seulement sur Windows)

Guide de codage des Script Siril

  • Unlike most python environments, Siril scripts run directly from Siril and the end user may not typically know how to access or how to use the python venv from outside Siril. This means that some tasks that are fairly trivial in typical python scenarios, such as installing packages, become harder. The user cannot be expected to access the command line and install packages themselves using python3 -m pip install.

    • Le module fournit donc la méthode «ensure_installed(). Celle-ci utilise pip pour s'assurer que les modules sont installés afin qu'ils puissent être importés.

  • Siril scripts should always provide the author's name, copyright details / license information and contact details such as a YouTube channel, website or forum where they can be contacted in regard to their script. This is advisory for independently distributed scripts and mandatory for any scripts that are submitted to the scripts repository. If you write a script, you are responsible for supporting it.

  • Au fur et à mesure que le répertoire s'enrichit et que l'API évolue, tous les scripts publiés ne seront pas nécessairement toujours compatibles avec toutes les versions de Siril qui seront utilisé :

    • If your script uses Siril commands, you should use the requires Siril command. This can be called directly in a Siril Script File, or it can be called from a Python script using SirilInterface.cmd("requires", "min_version", {"max_version"}) (max_version is optional) but can be used to ensure scripts designed for older versions of Siril no longer show as applicable to newer versions if the command syntax has changed.

    • If your script uses any features of the Siril python module added since the initial release, you should call the sirilpy.check_module_version() method to ensure the installed version meets the requriements of your script. The versions at which features were added will be listed in the API documentation for all features added after the initial public release.

    • The code that populates the Siril view of the scripts repository will automatically filter out scripts whose Siril version or python module version requirements are not met.

    • If new classes or methods are added to the module after its initial public release the version at which they were introduced will be annotated in the docstring and the online documentation generated from it.

  • Siril targets Linux, Windows and MacOS. Script writers are encouraged, where possible, to ensure that their scripts run correctly on all three OSes.

Sirilpy Connection

This submodule provides the main SirilInterface class used for communication between Siril and the python script. All its members are made available at the module root level, there is no need to import connection separately.

Connection module for Siril, providing the ability to connect to a running Siril instance and communicate with it. Includes an extensive range of methods that can be used to get and set data from / to Siril.

class sirilpy.connection.SirilInterface

Bases : object

SirilInterface is the main class providing an interface to a running Siril instance and access to methods to interact with it through Siril's inbuilt command system and accessing image and sequence data.

analyse_image_from_file(filepath)

Request Siril to load an image from a file and analyse it. This method does not change the image currently loaded in Siril. Any image format supported by Siril is supported. An ImageAnalysis object is returned, containing parameters that may be used to assess the quality of an image for use in culling.

Paramètres:

filepath (str) -- String specifying the path to the image file to load.

Type renvoyé:

ImageAnalysis

Renvoie:

ImageAnalysis object containing quality metrics for the analysed image.

Lève:
  • FileNotFoundError -- if the specified file does not exist,

  • DataError -- on receipt of incorrect data,

  • SirilError -- si une erreur est survenue.

clear_image_bgsamples()

Clears all background sample points from the image.

clear_undo_history()

Clears the image undo history, if there is undo history to be cleared

cmd(*args)

Send a command to Siril to be executed. The range of available commands can be found by checking the online documentation. The command and its arguments are provided as a list of strings.

Paramètres:

*args (str) -- Variable number of string arguments to be combined into a command

Lève:
  • DataError -- If no response (or an incorrect response) was received,

  • CommandError -- If the command returns an error status code,

  • SirilError -- Si une autre erreur est survenue durant l'exécution.

Exemple

siril.cmd("ght", "-D=0.5", "-b=2.0")
command_error_message(status_code)

Provides a string describing the return status from a Siril command.

Paramètres:

status_code (CommandStatus) -- The status code returned by the Siril command handler, or by the CommandError exception.

Renvoie:

A string providing a description of the error code returned by a Siril command, for use in exception handling.

Type renvoyé:

str

confirm_messagebox(title, message, confirm_label)

Create a modal confirmation message dialog in Siril and wait for the response.

Paramètres:
  • title (str) -- The title to display in the message box (up to 256 characters)

  • message (str) -- The message to display in the message box (up to 1021 characters)

  • confirm_label (str) -- The label to display in the message box confirmation button (OK, Yes, Confirm etc.) (Up to 24 characters)

Renvoie:

True if the message box confirmation button was clicked, False otherwise

Type renvoyé:

bool

Lève:
connect()

Establish a connection to Siril based on the pipe or socket path.

Type renvoyé:

bool

Renvoie:

True en cas de succès

Lève:

SirilConnectionError -- si une erreur de connexion s'est produite

create_new_seq(seq_root)

Creates a new .seq file with all images named seq_rootXXXXX.ext located in the current home folder. If a sequence with the same name is already loaded in Siril, it will not be recreated. This only works for FITS files, not FITSEQ nor SER. The newly created sequence is not loaded in Siril.

Paramètres:

seq_root (str) -- Le nom racine de la séquence à créer.

Renvoie:

True if the sequence was successfully created, False otherwise.

Type renvoyé:

bool

Lève:

SirilError -- si une erreur est survenue.

disconnect()

Closes the established socket or pipe connection. Note there is not usually any need to close this unless for some reason you wish to close a connection and subsequently reopen another one. This method is automatically called at script termination using an atexit handler so there is no need to do so manually. Calling this method will reset the progress bar.

Lève:

SirilConnectionError -- si la connexion ne peut pas être fermée.

error_messagebox(my_string, modal=False)

Send an error message to Siril. The maximum message length is 1022 bytes: longer messages will be truncated (but this is more than enough for an error message box). Note that the error message box is not modal by default: this is intended for displaying an error message more prominently than using the Siril log prior to quitting the application.

Paramètres:
  • my_string (str) -- Le message à afficher dans la boîte de message d'erreur

  • modal (Optional[bool]) -- Sets whether or not the message box should be modal and wait for completion or non-modal and allow the script to continue execution. Note that although a modal message box will block execution of the script, if a TKinter main loop is running events will continue to queue up, so if the message box is triggered by clicking a button then the user may click it while the message box is shown and trigger a second message box which will display immediately the first one is closed.

Renvoie:

Vrai si l'erreur a été affichée avec succès, faux dans le cas contraire

Type renvoyé:

bool

Lève:

SirilError -- si une erreur est survenue.

get_image(with_pixels=True, preview=False)

Request a copy of the current image open in Siril. Requires a single image to be loaded.

Paramètres:
  • with_pixels (Optional[bool]) -- booléen facultatif indiquant s'il faut récupérer les données pixel sous forme d'un NumPy array ou uniquement les métadonnées de l'image. La valeur par défaut est True

  • preview (Optional[bool]) -- booléen facultatif indiquant s'il faut obtenir les données pixel sous forme d'aperçu (i.e. des données étirées automatiquement sur 8 bits) ou sous forme de données image réelles. La valeur par défaut est False (i.e. des données image réelles)

Type renvoyé:

Optional[FFit]

Renvoie:

Objet FFit contenant les métadonnées de l'image et (éventuellement) les données pixel, ou None si une erreur s'est produite

Lève:
  • NoImageError -- si aucune image n'est chargée dans Siril

  • SirilError -- si une erreur de décodage se produit

get_image_bgsamples()

Request background samples data from Siril.

Type renvoyé:

Optional[List[BGSample]]

Renvoie:

List of BGSamples background samples, with each set of coordinates expressed as a tuple[float, float], or None if no background samples have been set.

Lève:
  • NoImageError -- Si aucune image n'est actuellement chargée,

  • DataError -- à la réception de mauvaise données,

  • SirilError -- Pour les autres erreurs survenant lors de la récupération des données,

get_image_filename()

Request the filename of the loaded image from Siril. Requires a single image to be loaded.

Type renvoyé:

Optional[str]

Renvoie:

Le nom de fichier comme une chaîne de caractère.

Lève:
get_image_fits_header(return_as='str')

Retrieve the full FITS header of the current image loaded in Siril. Requires a single image to be loaded.

Paramètres:

return_as -- Optional string specifying the format of the returned header. Can be 'str' for a string or 'dict' for a dictionary.

Renvoie:

The image FITS header as a string, or None if there is no header. dict: The image FITS header as a dictionary, or None if there is no header. None: If the header is empty or not available.

Type renvoyé:

str

Lève:
  • NoImageError -- Si aucune image n'est actuellement chargée,

  • SirilError -- Pour les autres erreurs survenant lors de la récupération des données,

get_image_history()

Retrieve history entries in the FITS header of the current loaded Siril image using shared memory. Requires a single image to be loaded.

Paramètres:

none.

Renvoie:

Les entrées HISTORY dans l'entête FITS sous forme de liste de chaînes, ou None s'il n'y a pas de mots-clés HISTORY.

Type renvoyé:

list

Lève:
  • NoImageError -- Si aucune image n'est actuellement chargée,

  • SirilError -- Pour les autres erreurs survenant lors de la récupération des données.

get_image_iccprofile()

Retrieve the ICC profile of the current Siril image using shared memory. Requires a single image to be loaded.

Args: none.

Renvoie:

The image ICC profile as a byte array, or None if the current image has no ICC profile.

Type renvoyé:

bytes

Lève:
get_image_keywords()

Request FITS keywords data from Siril as a FKeywords object. Requires a single image to be loaded.

Type renvoyé:

Optional[FKeywords]

Renvoie:

Objet FKeywords contenant les mots-clés FITS, ou None si une erreur s'est produite

Lève:

SirilError -- si une erreur de décodage se produit.

get_image_pixeldata(shape=None, preview=False, linked=False)

Retrieves the pixel data from the image currently loaded in Siril.

Paramètres:
  • shape (Optional[list[int]]) -- Optional list of [x, y, w, h] specifying the region to retrieve. If provided, gets pixeldata for just that region. If None, gets pixeldata for the entire image.

  • preview (Optional[bool]) -- booléen facultatif indiquant s'il faut obtenir les données pixel sous forme d'aperçu (i.e. des données étirées automatiquement sur 8 bits) ou sous forme de données image réelles. La valeur par défaut est False (i.e. des données image réelles)

  • linked (Optional[bool]) -- optional bool specifying whether the autostretch preview should be linked or unlinked. If preview == False then this option is ignored.

Renvoie:

Les données d'image en format numpy array

Type renvoyé:

numpy.ndarray

Lève:
  • NoImageError -- Si aucune image n'est actuellement chargée,

  • ValueError -- Si une taille invalide est fournie,

  • DataError -- si le tableau ne peut pas être redimensionné à la bonne dimension,

  • SirilError -- Pour les autres erreurs survenant lors de la récupération des données pixel,

get_image_shape()

Demande la taille de l'image à Siril.

Type renvoyé:

Optional[Tuple[int, int, int]]

Renvoie:

A tuple (channels, height, width) representing the shape of the image, or None if no image shape is available to return.

Raises: SirilError: if an error occurred.

get_image_stars(channel=None)

Request star model PSF data from Siril.

Paramètres:

channel (Optional[int]) -- Optional int specifying the channel to retrieve from. If provided 0 = Red / Mono, 1 = Green, 2 = Blue. If the channel is omitted the default behavior will be used: channel 0 for mono images, channel 1 (green) for color images. channel requires sirilpy v1.0.8 or higher.

Type renvoyé:

List[PSFStar]

Renvoie:

List of PSFStar objects containing the star data, or None if no stars can be found. If stars have already been detected using the findstar command then this list will be returned, otherwise automatic star detection will be attempted with the current star finder settings.

Lève:
  • NoImageError -- Si aucune image n'est actuellement chargée,

  • ValueError -- If an invalid channel is provided,

  • SirilError -- Pour les autres erreurs survenant lors de la récupération des données,

get_image_stats(channel)

Request image statistics from Siril for a specific channel. Requires a single image to be loaded.

Paramètres:

channel (int) -- Integer specifying which channel to get statistics for (typically 0, 1, or 2)

Type renvoyé:

Optional[ImageStats]

Renvoie:

ImageStats object containing the statistics, or None if no stats are available for the selected channel

Lève:
get_image_unknown_keys()

Retrieve the unknown key in a FITS header of the current loaded Siril image using shared memory. Requires a single image to be loaded.

Paramètres:

none.

Renvoie:

The unknown keys as a string, or None if there are no unknown keys.

Type renvoyé:

bytes

Lève:
  • NoImageError -- Si aucune image n'est actuellement chargée,

  • SirilError -- Pour les autres erreurs survenant lors de la récupération des données.

get_selection_star(shape=None, channel=None, assume_centred=False)

Retrieves a PSFStar star model from the current selection in Siril. Only a single PSFStar is returned: if there are more than one in the selection, the first one identified by Siril's internal star detection algorithm is returned. Update: from sirilpy 1.0.4 this method uses Siril's photometry functions to try to provide photometrically accurate values for PSFStar.mag, PSFStar.s_mag and PSFStar.SNR. If photometry succeeded and no saturated pixels were detected then PSFStar.phot_is_valid will be True, otherwise it will be False. :type shape: Optional[list[int]] :param shape: Optional list of [x, y, w, h] specifying the selection to

retrieve from. w x h must not exceed 300 px x 300 px. If provided, looks for a star in the specified selection If None, looks for a star in the selection already made in Siril, if one is made.

Paramètres:
  • channel (Optional[int]) -- Optional int specifying the channel to retrieve from. If provided 0 = Red / Mono, 1 = Green, 2 = Blue. If the channel is omitted the current viewport will be used if in GUI mode, or if not in GUI mode the method will fall back to channel 0

  • assume_centred (bool) -- Optional bool specifying whether to assume the star is already centred in the selection. Defaults to False.

Renvoie:

the PSFStar object representing the star model, or None if

no star is detected in the selection.

Type renvoyé:

PSFStar

Lève:
  • ValueError -- Si une taille invalide est fournie,

  • NoImageError -- Si aucune image n'est chargé,

  • SirilConnectionError -- Si une erreur de communication se produit,

  • SirilError -- If any other error occurred during execution.

get_selection_stats(shape=None, channel=None)

Retrieves statistics for the current selection in Siril. Requires a single image or a sequence to be loaded.

Paramètres:
  • shape (Optional[list[int]]) -- Optional list of [x, y, w, h] specifying the selection to retrieve from. If provided, looks for a star in the specified selection If None, looks for a star in the selection already made in Siril, if one is made.

  • channel (Optional[int]) -- Optional int specifying the channel to retrieve from. If provided 0 = Red / Mono, 1 = Green, 2 = Blue. If the channel is omitted the current viewport will be used if in GUI mode, or if not in GUI mode the method will fall back to channel 0

Renvoie:

the ImageStats object representing the selection statistics.

Type renvoyé:

ImageStats

Lève:
  • SirilError -- If an error occurred during processing,

  • ValueError -- Si une forme non valide est fournie.

get_seq()

Demander les métadonnées de la séquence actuellement chargée dans Siril.

Type renvoyé:

Optional[Sequence]

Renvoie:

Objet de séquence contenant les métadonnées de la séquence actuelle, ou None si une erreur s'est produite

Lève:
get_seq_distodata(channel)

Request sequence distortion data from Siril

channel: Integer specifying which channel to get registration data for (typically 0, 1, or 2)

Type renvoyé:

Optional[DistoData]

Renvoie:

DistoData object containing the channel distortion parameters, or None if an error occurred

Lève:
get_seq_frame(frame, with_pixels=True, preview=False, linked=False)

Request sequence frame as a FFit from Siril. The keywords, statistics, header and other metadata are always returned: if an ICC profile is present, this will also be populated in the resulting FFit, and optionally the pixel data can also be returned.

Paramètres:
  • frame (int) -- Integer specifying which frame in the sequence to retrieve data for (between 0 and Sequence.number - 1). This uses a 0-based indexing scheme, i.e. the first frame is frame number 0, not frame numer 1.

  • with_pixels (Optional[bool]) -- bool specifying whether or not to return the pixel data for the frame (default is True).

  • preview (Optional[bool]) -- bool specifying whether or not to return the real pixel data or an autostretched uint8_t preview version. Only has an effect in conjunction with with_pixels = True

Type renvoyé:

Optional[FFit]

Renvoie:

FFit object containing the frame data

Lève:
get_seq_frame_filename(frame)

Request the filename of the specified frame of the loaded sequence from Siril. Requires a sequence to be loaded.

Paramètres:

frame (int) -- Specifies the frame index. This uses a 0-based indexing scheme, i.e. the first frame is frame number 0, not frame numer 1.

Type renvoyé:

Optional[str]

Renvoie:

Le nom de fichier comme une chaîne de caractère.

Lève:
get_seq_frame_header(frame, return_as='str')

Retrieve the full FITS header of an image from the sequence loaded in Siril.

Paramètres:
  • frame (int) -- Integer specifying which frame in the sequence to retrieve data for (between 0 and Sequence.number - 1). This uses a 0-based indexing scheme, i.e. the first frame is frame number 0, not frame numer 1.

  • return_as -- Optional string specifying the format of the returned header. Can be 'str' for a string or 'dict' for a dictionary.

Renvoie:

The image FITS header as a string, or None if there is no header. dict: The image FITS header as a dictionary, or None if there is no header. None: If the header is empty or not available.

Type renvoyé:

str

Lève:
  • NoSequenceError -- Si aucune séquence n'est actuellement chargé,

  • SirilError -- Pour les autres erreurs survenant lors de la récupération des données,

get_seq_frame_pixeldata(frame, shape=None, preview=False, linked=False)

Retrieves the pixel data from a frame in the sequence currently loaded in Siril.

Paramètres:
  • frame (int) -- selects the frame to retrieve pixel data from. This uses a 0-based indexing scheme, i.e. the first frame is frame number 0, not frame numer 1.

  • shape (Optional[List[int]]) -- Optional list of [x, y, w, h] specifying the region to retrieve. If provided, gets pixeldata for just that region. If None, gets pixeldata for the entire image.

  • preview (Optional[bool]) -- optional bool specifying whether to get pixeldata as a preview (i.e. 8-bit autostretched data) or as real image data. Defaults to False (i.e. real image data).

  • linked (Optional[bool]) -- optional bool specifying whether the autostretched preview should be linked or unlinked. This option is ignored if preview is not True

Renvoie:

Les données d'image en format numpy array

Type renvoyé:

numpy.ndarray

Lève:
  • ValueError -- Si une taille invalide est fournie,

  • DataError -- si le tableau ne peut pas être redimensionné à la bonne dimension,

  • SirilError -- Pour les autres erreurs survenant lors de la récupération des données des pixels.

get_seq_imgdata(frame)

Demander les métadonnées des images de la séquence à Siril.

Paramètres:

frame (int) -- Integer specifying which frame in the sequence to get image metadata for (between 0 and Sequence.number). This uses a 0-based indexing scheme, i.e. the first frame is frame number 0, not frame numer 1.

Type renvoyé:

Optional[ImgData]

Renvoie:

Objet ImgData contenant les métadonnées de l'image, ou None si une erreur s'est produite

Lève:
get_seq_regdata(frame, channel)

Request sequence frame registration data from Siril.

Paramètres:
  • frame (int) -- Integer specifying which frame in the sequence to get registration data for (between 0 and Sequence.number). This uses a 0-based indexing scheme, i.e. the first frame is frame number 0, not frame numer 1.

  • channel (int) -- Integer specifying which channel to get registration data for (typically 0, 1, or 2)

Type renvoyé:

Optional[RegData]

Renvoie:

RegData object containing the registration data, or None if no registration data is available for the specified frame and channel

Lève:
get_seq_stats(frame, channel)

Demander les statistiques sur les images de la séquence à Siril.

Paramètres:
  • frame (int) -- Integer specifying which frame in the sequence to get statistics data for (between 0 and Sequence.number). This uses a 0-based indexing scheme, i.e. the first frame is frame number 0, not frame numer 1.

  • channel (int) -- Integer specifying which channel to get statistics for (typically 0, 1, or 2)

Type renvoyé:

Optional[ImageStats]

Renvoie:

Objet ImageStats contenant les statistiques, ou None si une erreur s'est produite

Lève:
get_siril_active_vport()

Request the active viewport from Siril.

Renvoie:

  • sirilpy.SirilVport.RED / sirilpy.SirilVport.MONO

  • sirilpy.SirilVport.GREEN,

  • sirilpy.SirilVport.BLUE,

  • sirilpy.SirilVport.RGB

Note that RED and MONO share the same IntEnum value, so there is no difference between a test for one and the other; the two enum labels are provided solely to aid code legibility.

Type renvoyé:

A SirilVport representing the active vport

Lève:
  • DataError -- si aucune réponse n'est reçue ou si la réponse n'est pas valide,

  • SirilError -- si une erreur est survenue.

get_siril_config(group, key)

Demandez une valeur de configuration à Siril.

Paramètres:
  • group (str) -- Configuration group name,

  • key (str) -- Configuration key name within the group (Available values for group and key can be determined using the "get -A" command)

Type renvoyé:

Union[bool, int, float, str, List[str], None]

Renvoie:

La valeur de configuration avec le type Python correspondant, ou None si une erreur s'est produite.

Lève:
  • DataError -- si un type de configuration inconnu est détecté,

  • SirilError -- si une erreur s'est produite lors de la récupération de la valeur de configuration demandée

get_siril_configdir()

Demander le répertoire de configuration utilisateur utilisé par Siril.

Type renvoyé:

str

Renvoie:

Le répertoire de configuration de l'utilisateur sous forme de chaîne de caractères.

Lève:
get_siril_display_iccprofile()

Récupérer le profil ICC de l'écran de Siril.

Args: none.

Renvoie:

Le profil ICC de l'affichage sous forme de tableau d'octets, ou None si Siril fonctionne en mode sans interface graphique.

Type renvoyé:

bytes

Lève:
get_siril_log()

Récupérer l'intégralité des logs Siril sous forme de chaîne de texte.

Renvoie:

Le texte des logs Siril.

Type renvoyé:

str

Lève:

SirilError -- For errors during data retrieval,

get_siril_panzoom()

Request the pan and zoom state from Siril.

Type renvoyé:

Tuple[float, float, float]

Renvoie:

A tuple (x offset, y offset, zoomlevel) representing the current image pan and zoom state.

Lève:

SirilError -- si une erreur est survenue.

get_siril_selection()

Demandez la sélection d'images à Siril.

Type renvoyé:

Optional[Tuple[int, int, int, int]]

Renvoie:

A tuple (x, y, height, width) representing the current selection, or None if no selection is made.

Lève:

SirilError -- si une erreur est survenue.

get_siril_slider_state(float_range=False)

Request the display slider state from Siril.

Type renvoyé:

Tuple[int, int, SlidersMode]

Renvoie:

A tuple (min, max, slider mode) representing the current slider state.

Lève:

SirilError -- si une erreur est survenue.

get_siril_stf()

Request the Screen Transfer Function in use in Siril.

Type renvoyé:

STFType

Renvoie:

A STFType representing the current STF state.

Lève:

SirilError -- si une erreur est survenue.

get_siril_stf_linked()

Determine whether the AutoStretch STF is configured to be linked or not

Type renvoyé:

bool

Renvoie:

A bool representing the current STF channel-linked state.

Lève:

SirilError -- si une erreur est survenue.

get_siril_systemdatadir()

Request the system data directory used by Siril.

Type renvoyé:

Optional[str]

Renvoie:

The system data directory as a string.

Lève:
get_siril_userdatadir()

Request the user data directory used by Siril.

Type renvoyé:

str

Renvoie:

The user data directory as a string.

Lève:
get_siril_wd()

Request the current working directory from Siril.

Type renvoyé:

str

Renvoie:

The current working directory as a string.

Lève:
  • DataError -- si aucune réponse n'a été obtenue,

  • SirilError -- pour toutes les autres erreurs.

image_lock()

A context manager that handles claiming and releasing the processing thread.

This method is designed to be used with a with statement to ensure that the thread is properly claimed before processing and released after processing, even if an exception occurs during processing. It is preferable to use this context manager rather than manually calling claim_thread() and release_thread() as the context manager will ensure correct cleanup if an exception occurs.

Note that the image_lock() context should only be entered when the script itself is operating on the Siril image data. If the script is calling a Siril command to alter the Siril image then the context must not be entered or the Siril command will be unable to acquire the processing thread and will fail.

Exemple :

try:
    with siril.image_lock():
        # Get image data
        image_data = self.get_image_pixeldata()
        # Process image data
        processed_data = some_processing_function(image_data)
        # Set the processed image data
        siril.set_image_pixeldata(processed_data)
except ProcessingThreadBusyError:
    # Handle busy thread case
    pass
except ImageDialogOpenError:
    # Handle open dialog case
    pass
Lève:
info_messagebox(my_string, modal=False)

Send an information message to Siril. The maximum message length is 1022 bytes: longer messages will be truncated. This is intended for displaying informational messages more prominently than using the Siril log.

Paramètres:
  • my_string (str) -- The message to display in the info message box

  • modal (Optional[bool]) -- Sets whether or not the message box should be modal and wait for completion or non-modal and allow the script to continue execution. Note that although a modal message box will block execution of the script, if a TKinter main loop is running events will continue to queue up, so if the message box is triggered by clicking a button then the user may click it while the message box is shown and trigger a second message box which will display immediately the first one is closed.

Renvoie:

True if the info was successfully displayed, False otherwise

Type renvoyé:

bool

Lève:

SirilError -- si une erreur est survenue.

is_cli()

Check if the current instance is running in CLI mode. This method is useful to detect how the script was invoked and whether to show or not a GUI. This is False when the script is called by clicking in the Script menu, True otherwise.

Renvoie:

True if running in CLI mode, False otherwise.

Type renvoyé:

bool

is_image_loaded()

Check if a single image is loaded in Siril.

Renvoie:

True if a single image is loaded, False if a single image is not loaded

Type renvoyé:

bool

Lève:
is_sequence_loaded()

Vérifie si une séquence est chargé dans Siril.

Renvoie:

True if a sequence is loaded, False if a sequence is not loaded

Type renvoyé:

bool

Lève:
load_image_from_file(filepath, with_pixels=True, preview=False, linked=False)

Request Siril to load an image from a file and transfer it to sirilpy. This method does not change the image currently loaded in Siril. Any image format supported by Siril is supported. This may be used as an alternative to loading an image using astropy.io.fits, however perhaps the main benefit to using it is that it supports the preview option which can be used to obtain an 8-bit autostretched rendering of the image more quickly than is possible using astropy and applying an autostretch using numpy.

Paramètres:
  • filepath (str) -- String specifying the path to the image file to load.

  • with_pixels (Optional[bool]) -- bool specifying whether or not to return the pixel data for the image (default is True).

  • preview (Optional[bool]) -- bool specifying whether or not to return the real pixel data or an autostretched uint8_t preview version. Only has an effect in conjunction with with_pixels = True

  • linked (Optional[bool]) -- bool specifying whether the autostretch preview should be linked or not. Has no effect unless preview is True.

Type renvoyé:

Optional[FFit]

Renvoie:

FFit object containing the image data

Lève:
  • FileNotFoundError -- if the specified file does not exist,

  • DataError -- on receipt of incorrect data,

  • SirilError -- si une erreur est survenue.

log(my_string, color=LogColor.DEFAULT)

Send a log message to Siril. The maximum message length is 1022 bytes: longer messages will be truncated.

Paramètres:
  • my_string (str) -- Le message à loger

  • color (LogColor) -- Defines the text color, defaults to white. See the documentation

  • which (for LogColor for an explanation of which colors should be used for)

  • purposes.

Lève:

SirilError -- si la commande échoue

Type renvoyé:

bool

open_dialog(dialog)

Opens a Siril GUI dialog. Introduced in sirilpy version 1.0.20.

Paramètres:

dialog (DialogID) -- Specifies the dialog to open.

Renvoie:

True if the dialog-opening action succeeded False if the dialog-opening action failed (e.g. because the criteria were not met)

Lève:
  • TypeError -- if the parameter is not a DialogID.

  • SirilError -- if the method is called headless or an error occurs.

overlay_add_polygon(polygon)

Adds a user polygon to the Siril display overlay :type polygon: Polygon :param polygon: Polygon defining the polygon to be added

Renvoie:

les entrées mise à jours avec l'ID assigné par Siril

Type renvoyé:

Polygon

Lève:
overlay_clear_polygons()

Clears all user polygons from the Siril overlay

Renvoie:

True if the command succeeded, False otherwise

Type renvoyé:

bool

Lève:
overlay_delete_polygon(polygon_id)

Deletes a single user polygon from the Siril overlay, specified by ID

Paramètres:

id -- int specifying the polygon ID to be deleted

Lève:

SirilError -- en cas d'échec

overlay_draw_polygon(color=16711744, fill=False)

Enters a mode where the user can draw a Polygon in the Siril window by clicking the main mouse button and dragging. Releasing the mouse button finalises and closes the polygon.

Paramètres:
  • color -- uint32 specifying packed RGBA values. Default: 0x00FF0040, 75% transparent green)

  • fill -- bool specifying whether or not to fill the polygon (default: False)

overlay_get_polygon(polygon_id)

Gets a single user polygon from the Siril overlay, specified by ID

Paramètres:

id -- int specifying the polygon ID to be retrieved. The special ID -1 will

retrieve the most recently added polygon.

Renvoie:

the specified Polygon if it exists, None otherwise

Type renvoyé:

Polygon

Lève:

SirilError -- en cas d'échec

overlay_get_polygons_list()

Gets a List of all user polygons from the Siril overlay

Renvoie:

the list of Polygon if some exist, None otherwise

Type renvoyé:

List[Polygon]

Lève:
pix2radec(x, y)

Converts a pair of pixel coordinates into RA and dec coordinates using the WCS of the image loaded in Siril. This requires that an image is loaded in Siril and that it has been platesolved (i.e. it has a WCS solution).

Paramètres:
  • x (float) -- float: provides the x coordinate to be converted

  • y (float) -- float: provides the y coordinate to be converted

Renvoie:

(RA, Dec) as a Tuple of two floats.

Type renvoyé:

Tuple[float, float]

Lève:
  • NoImageError -- Si aucune image ou séquence n'est chargé,

  • ValueError -- If the image or loaded sequence frame is not plate solved,

  • SirilError -- For errors during pix2radec execution.

radec2pix(ra, dec)

Converts a pair of RA,dec coordinates into image pixel coordinates using the WCS of the image loaded in Siril. This requires that an image is loaded in Siril and that it has been platesolved (i.e. it has a WCS solution).

Paramètres:
  • ra (float) -- float: provides the RA coordinate to be converted

  • dec (float) -- float: provides the dec coordinate to be converted

Renvoie:

[x,y] comme un Tuple de deux nombres flottants.

Type renvoyé:

Tuple[float, float]

Lève:
  • NoImageError -- Si aucune image ou séquence n'est chargé,

  • ValueError -- If the image or loaded sequence frame is not plate solved,

  • SirilError -- For errors during radec2pix execution.

redo()

Redoes the last undone operation, if there is an undo history and an undone operation available to be redone.

reset_progress()

Réinitialise la barre de progression de Siril.

Paramètres:

none

Lève:

SirilError -- For any errors.

Type renvoyé:

bool

save_image_file(data, header=None, filename=None)

Save image pixeldata and metadata to a FITS file. This uses Siril to save the image and can therefore be used to avoid a script dependency on astropy if it is only required for saving an image. This allows images to be saved directly from python without having to use set_image_pixeldata() and set_image_metadata_from_header_string() and saving the Siril image. It support processing multiple images without affecting the image currently loaded in Siril.

Paramètres:
  • data -- Either a numpy.ndarray containing the image data (must be 2D or 3D array with dtype float32 or uint16), OR a FFit object containing both data and header.

  • header -- string containing the FITS header data. Required if data is a numpy array, ignored if data is a FFit object.

  • filename -- string containing the path where the file should be saved. Required if data is a numpy array. If data is a FFit object and filename is None, will use fit.filename.

Renvoie:

True en cas de succès, False dans le cas contraire

Type renvoyé:

bool

Lève:
  • ValueError -- if the input array or header is invalid,

  • TypeError -- if invalid parameter types are provided,

  • SirilError -- si une erreur s'est produite lors du traitement de la commande.

Exemples

# Using numpy array and header string siril.save_image_file(data_array, header_string, "output.fit")

# Using FFit object siril.save_image_file(fit, filename="output.fit")

# Using FFit object with its own filename siril.save_image_file(fit)

set_image_bgsamples(points, show_samples=False, recalculate=True)

Serialize a set of background sample points and send via shared memory. Points can be provided either as: - List of (x,y) Tuples: BGSamples are created with these positions and Siril will automatically compute the statistics. - List of BGSample objects: The complete sample data is sent to Siril. By default Siril will recalculate statistics for the sample points on receipt, but this can be overridden with the argument recalculate=False

Paramètres:
  • points (Union[List[Tuple[float, float]], List[BGSample]]) -- List of sample points, either as (x,y) tuples or BGSample objects

  • show_samples (bool) -- Whether to show the sample points in Siril

  • recalculate -- Whether to recalculate the sample points once set. This only applies if the sample points are provided as a List of BGSamples, in which case it defaults to True. If the sample points are provided as a List of (x,y) Tuples then the parameter has no effect. Setting recalculate=False is usually a bad idea but the option is provided to support potential advanced uses where the values are adjusted in python code to manipulate the background fit.

Returns: True if the command succeeded, otherwise False

Lève:
  • NoImageError -- si aucune image n'est chargée dans Siril,

  • ValueError -- if samples do not have valid positions,

  • SirilError -- if there was a Siril error in handling the command.

set_image_filename(filename)

Set the image filename in Siril. :type filename: str :param filename: the image filename to set :type filename: str

Lève:
  • SirilError -- si une erreur est survenue.

  • ValueError -- si les paramètres ne sont pas correctement fournis.

Renvoie:

True if the filename was set successfully

Type renvoyé:

bool

set_image_iccprofile(iccprofile)

Set the image ICC profile in Siril

Paramètres:
  • iccprofile (bytes) -- The ICC profile to send to Siril. This will

  • profile (replace an existing ICC)

  • None (if one is set. If)

:param : :param any existing image ICC profile will be removed.:

Returns: True if the command succeeded, otherwise False

Lève:
  • NoImageError -- si aucune image n'est chargée dans Siril,

  • ValueError -- if iccprofile is not valid type,

  • SirilError -- if there was a Siril error in handling the command.

set_image_metadata_from_header_string(header)

Send image metadata to Siril from a FITS header. The header can be obtained from a sirilpy FFit.header or alternatively from a FITS file obened from disk using astropy.fits.

Exemple :

hdul = fits.open('your_fits_file.fits')
# Get the header from the primary HDU (or any other HDU you want)
header = hdul[0].header
# Convert the header to string
header_string = header.tostring(sep='\\n')
# Send the metadata to Siril
siril.set_image_metadata_from_header_string(header_string)
Paramètres:

header (str) -- string containing the FITS header data

Renvoie:

True en cas de succès, False dans le cas contraire

Type renvoyé:

bool

Lève:
  • TypeError -- paramètre invalide fourni,

  • NoImageError -- si aucune image n'est chargée dans Siril,

  • SirilError -- si une erreur est survenue.

set_image_pixeldata(image_data)

Envoyer les données d'image à Siril à l'aide de la mémoire partagée.

Paramètres:

image_data (ndarray) -- numpy.ndarray containing the image data. Must be 2D (single channel) or 3D (multi-channel) array with dtype either np.float32 or np.uint16.

Lève:
  • NoImageError -- si aucune image n'est chargée dans Siril,

  • ValueError -- Si le tableau d'entré est invalide,

  • SirilError -- si une erreur s'est produite lors du traitement de la commande.

Type renvoyé:

bool

set_seq_frame_incl(index, incl)

Set whether given frame(s) are included in the currently loaded sequence in Siril. This method is intended for use in creating custom sequence filters.

Paramètres:
  • index (Union[int, List[int]]) -- integer or list of integers specifying which frame(s) to set the inclusion status for. This uses a 0-based indexing scheme, i.e. the first frame is frame number 0, not frame number 1. Passing a list is available since sirilpy 1.0.17

  • incl (bool) -- bool specifying whether the frame(s) are included or not.

Lève:
  • NoSequenceError -- si aucune séquence n'est chargée dans Siril,

  • TypeError -- if index is not an int or list of ints,

  • SirilError -- en cas d'échec.

set_seq_frame_pixeldata(index, image_data, prefix)

Send sequence frame image data to Siril using shared memory. Note that this method only works with sequences of FITS images: it does not work with FITSEQ, SER or AVI single-file sequences. The image_lock() context manager is not required in order to use this method.

Paramètres:
  • index (int) -- integer specifying which frame to set the pixeldata for. This uses a 0-based indexing scheme, i.e. the first frame is frame number 0, not frame numer 1.

  • image_data (ndarray) -- numpy.ndarray containing the image data. Must be 2D (single channel) or 3D (multi-channel) array with dtype either np.float32 or np.uint16.

  • prefix (str) -- String prefix to use when saving the file to make a new sequence. Note that saving sequence frames with a new prefix does not by itself create a new sequence: once all the frames have been saved with the new sequence prefix, sirilpy.SirilInterface.create_new_seq() must be called to create the actual sequence file. Note that while it is permitted to pass prefix=None, this will overwrite the existing sequence and is not typically what is wanted, therefore the parameter is not optional and must be passed explicitly.

Lève:
  • NoSequenceError -- si aucune séquence n'est chargée dans Siril,

  • ValueError -- Si le tableau d'entré est invalide,

  • SirilError -- si une erreur s'est produite lors du traitement de la commande.

Type renvoyé:

bool

set_siril_pan(xoff, yoff)

Set the display offset (pan) in Siril to (xoff, yoff). :type xoff: float :param xoff: x display offset :type xoff: float :type yoff: float :param yoff: y display offset :type yoff: float

Lève:
  • SirilError -- si une erreur est survenue.

  • ValueError -- si les paramètres ne sont pas correctement fournis.

Renvoie:

True if the display offset was set successfully

Type renvoyé:

bool

set_siril_selection(x=None, y=None, w=None, h=None, selection=None)

Set the image selection in Siril using the provided coordinates and dimensions.

Paramètres:
  • x (Optional[int]) -- X-coordinate of the selection's top-left corner (must be provided with y, w, h)

  • y (Optional[int]) -- Y-coordinate of the selection's top-left corner (must be provided with x, w, h)

  • w (Optional[int]) -- Width of the selection (must be provided with x, y, h)

  • h (Optional[int]) -- Height of the selection (must be provided with x, y, w)

  • selection (Optional[Tuple[int, int, int, int]]) -- A tuple of (x, y, w, h) as returned by get_siril_selection()

Lève:
  • SirilError -- si une erreur est survenue.

  • ValueError -- si les paramètres ne sont pas correctement fournis.

Renvoie:

True if the selection was set successfully

Type renvoyé:

bool

set_siril_slider_lohi(lo=None, hi=None)

Set the slider values in Siril using the provided lo and hi values. If the sliders mode is not already set to USER, it is set to that mode as setting slider values is only relevant in that mode. :type lo: Union[float, int] :param lo: Low value for the slider (float [0,1] or uint16) :type hi: Union[float, int] :param hi: High value for the slider (float [0,1] or uint16)

Lève:
  • SirilError -- si une erreur est survenue.

  • ValueError -- si les paramètres ne sont pas correctement fournis.

Renvoie:

True if the slider state was set successfully

Type renvoyé:

bool

set_siril_slider_mode(mode)

Set the slider state in Siril using the provided lo, hi and mode values. :type mode: SlidersMode :param mode: SlidersMode enum value

Lève:
  • SirilError -- si une erreur est survenue.

  • ValueError -- si les paramètres ne sont pas correctement fournis.

Renvoie:

True if the slider state was set successfully

Type renvoyé:

bool

set_siril_stf(mode)

Set the screen transfer function in Siril using the provided enum value. :type mode: SlidersMode :param mode: STFType enum value

Lève:
  • SirilError -- si une erreur est survenue.

  • ValueError -- si les paramètres ne sont pas correctement fournis.

Renvoie:

True if the slider state was set successfully

Type renvoyé:

bool

set_siril_stf_linked(state)

Set the screen transfer function in Siril using the provided enum value. :type state: bool :param state: bool

Lève:
  • SirilError -- si une erreur est survenue.

  • ValueError -- si les paramètres ne sont pas correctement fournis.

Renvoie:

True if the slider state was set successfully

Type renvoyé:

bool

set_siril_zoom(zoom)

Set the display zoom. Passing any negative value will set 'zoom to fit'. :type zoom: float :param zoom: zoom level :type zoom: float

Lève:
  • SirilError -- si une erreur est survenue.

  • ValueError -- si les paramètres ne sont pas correctement fournis.

Renvoie:

True if the display offset was set successfully

Type renvoyé:

bool

undo()

Undoes the last operation, if there is an undo history available.

undo_save_state(my_string)

Saves an undo state. The maximum message length is 70 bytes: longer messages will be truncated. Requires a single image to be loaded.

Paramètres:

my_string (str) -- Le message à écrire dans le FITS HISTORY

Renvoie:

True if the message was successfully logged, False if a logging error occurred or None if the script is headless (undo does not happen when headless)

Type renvoyé:

Optional[bool]

Lève:

SirilError -- si une erreur est survenue.

update_progress(message, progress)

Send a progress update to Siril with a message and completion percentage.

Paramètres:
  • message (str) -- Message de statu à afficher

  • progress (float) -- Progress value in the range 0.0 to 1.0. The following special values can be used: -1.0 will pulsate the progress bar, and -2.0 will update the progress bar text but will not update the progress shown in the bar.

Lève:
  • ValueError -- If the progress argument is out of range,

  • SirilError -- Pour tout autre erreurs.

Type renvoyé:

bool

warning_messagebox(my_string, modal=False)

Send a warning message to Siril. The maximum message length is 1022 bytes: longer messages will be truncated. This is intended for displaying warning messages more prominently than using the Siril log.

Paramètres:
  • my_string (str) -- Le message à afficher dans la boite de message d'avertissement

  • modal (Optional[bool]) -- Sets whether or not the message box should be modal and wait for completion or non-modal and allow the script to continue execution. Note that although a modal message box will block execution of the script, if a TKinter main loop is running events will continue to queue up, so if the message box is triggered by clicking a button then the user may click it while the message box is shown and trigger a second message box which will display immediately the first one is closed.

Renvoie:

True si l'avertissement a correctement été affiché, False sinon

Type renvoyé:

bool

Lève:

SirilError -- si une erreur est survenue.

xy_plot(plot_data, display=True, save=False)

Serialize plot data and send via shared memory. See the sirilpy.plot submodule documentation for how to configure a PlotData object for use with SirilInterface.xy_plot()

Paramètres:
  • plot_metadata -- PlotMetadata object containing plot configuration

  • display -- booléen indiquant s'il faut afficher le graphique à l'écran (valeur par défaut : True)

  • save -- bool indicating whether to save to the file specified in PlotData.savename (defaults to False)

Lève:
  • DataError -- if invalid xy_plot data is received via shared memory,

  • SirilError -- Si une erreur se produit.

Sirilpy Data Models

This submodule provides dataclasses to represent the main Siril data structures. Most dataclasses have corresponding deserialization methods that are used by the SirilInterface methods. All its members are made available at the module root level, there is no need to import models separately.

class sirilpy.models.BGSample(x=None, y=None, position=None, size=25, **kwargs)

Bases : object

Python equivalent of the Siril background_sample struct. Used to hold background sample data obtained from Siril, or to generate or modify background sample data to set in Siril. A BGSample can be constructed as: - s1 = BGSample(x=1.0, y=2.0) - s2 = BGSample(position=(1.0, 2.0)) - s3 = BGSample(x=1.0, y=2.0, mean=0.5, size=31)

classmethod deserialize(data)

Deserialize a portion of a buffer into a BGSample object

Paramètres:

data (bytes) -- The full binary buffer containing BGSample data

Renvoie:

Un objet BGSample

Type renvoyé:

BGSample

Lève:
  • ValueError -- If the buffer slice size does not match the expected size.

  • struct.error -- If there is an error unpacking the binary data.

max: float = 0.0
mean: float = 0.0
median: Tuple[float, float, float] = (0.0, 0.0, 0.0)

Valeur médiane des canaux R, V et B. Pour les images mono, seul median[0] est utilisé.

min: float = 0.0
position: Tuple[float, float] | None = None

Position (x, y) en coordonnées image

size: int = 25

The default size matches the size of Siril bg samples.

valid: bool = True

Samples default to being valid

class sirilpy.models.DistoData(index=DistoType.DISTO_UNDEF, filename='', velocity=(0, 0))

Bases : object

Python equivalent of Siril disto_params structure

filename: str = ''

filename if DISTO_FILE or DISTO_MASTER (and optional for DISTO_FILE_COMET)

index: DistoType = 0

Spécifie le type de distortion

velocity: Tuple[float, float] = (0, 0)

shift velocity if DISTO_FILE_COMET

class sirilpy.models.FFit(bitpix=None, orig_bitpix=None, naxis=0, _naxes=(0, 0, 0), keywords=<factory>, checksum=False, header=None, unknown_keys=None, stats=<factory>, mini=0.0, maxi=0.0, neg_ratio=0.0, _data=None, top_down=False, _focalkey=False, _pixelkey=False, history=<factory>, color_managed=False, _icc_profile=None)

Bases : object

Python equivalent of Siril ffit (FITS) structure, holding image pixel data and metadata.

allocate_data()

Allocate memory for image data with appropriate type. self.width, self.height, self.naxis, self.naxes and self.dtype must be set before calling this method.

Lève:

ValueError -- if self.bitpix is not set to BitpixType.USHORT_IMG or BitpixType.FLOAT_IMG

ensure_data_type(target_type=None)

Ensure data is in the correct type with proper scaling

Paramètres:

target_type -- Optional np.dtype to convert to. If None, uses self.type

Lève:

ValueError -- if the conversion is between data types that are not internally used by Siril for calculation

estimate_noise(array, nullcheck=True, nullvalue=0.0)

Estimate the background noise in the input image using the sigma of first-order differences.

noise = 1.0 / sqrt(2) * RMS of (flux[i] - flux[i-1])

Paramètres:
  • array (np.ndarray) -- 2D array of image pixels (np.uint16 or np.float32).

  • nullcheck (bool) -- Si la valeur est True, vérifiez s'il y a des valeurs nulles.

  • nullvalue (Optional[float]) -- The value of null pixels (only used if nullcheck is True).

Renvoie:

Valeur estimé du bruit.

Type renvoyé:

float

Lève:

ValueError -- if the array is the wrong shape

get_channel(channel)

Get a specific channel of the pixel data. Note that this does not pull pixel data directly from the image loaded in Siril: that must previously have been obtained using get_image_pixeldata() or get_image()

Type renvoyé:

ndarray

update_stats()

Update image statistics for all channels. Note that this only updates the statistics based on the NumPy array representing pixel data in the python FFit object, it does not update the statistics of the image in Siril.

bitpix: BitpixType | None = None

FITS header specification of the image data type.

property channels: int

Image channels

checksum: bool = False

Whether Siril will write FITS data checksums for this file.

color_managed: bool = False

Specifies whether the image is color managed or not.

property data: ndarray | None

The pixel data of the current image loaded in Siril, stored as a NumPy array

header: str | None = None

L'entête FITS en temps que chaîne de caractère.

property height: int

Hauteur de l'image

history: list[str]

Contains a list of strings holding the HISTORY entries for this image.

property icc_profile: bytes | None

The ICC profile as raw bytes data. This may be converted for use by modules such as pillow which can handle ICC profiles.

keywords: FKeywords

A FKeywords object containing FITS header keywords.

maxi: float = 0.0

La valeur maximal à travers tous les canaux de l'image.

mini: float = 0.0

La valeur minimal à travers tous les canaux de l'image.

property naxes: Tuple[int, int, int]

The naxes tuple holds the image dimensions as width x height x channels. Note that the axis ordering differs between Siril representation as held in naxes and numpy representation as held in _data.shape (which is channels x height x width)

naxis: int = 0

Le nombre d'axes (2 pour une image mono, 3 pour une image RGB). Correspond au mot clé FITS NAXIS.

neg_ratio: float32 = 0.0

The ratio of negative pixels to the total pixels.

orig_bitpix: BitpixType | None = None

FITS header specification of the original image data type.

stats: List[ImageStats | None]

A list of ImageStats objects, one for each channel.

top_down: bool = False

Specifies the ROWORDER for this image. The FITS specification directs that FITS should be stored bottom-up, but many CMOS sensors are natively TOP_DOWN and capture software tends to save FITS images captured by these sensors as TOP_DOWN.

unknown_keys: str | None = None

All unknown FITS header keys as a string. This gives access to header cards that Siril does not use internally.

property width: int

Largeur de l'image

class sirilpy.models.FKeywords(bscale=1.0, bzero=0.0, lo=0, hi=0, flo=0.0, fhi=0.0, program='', filename='', row_order='', filter='', image_type='', object='', instrume='', telescop='', observer='', bayer_pattern='', sitelat_str='', sitelong_str='', focname='', date=None, date_obs=None, data_max=0.0, data_min=0.0, pixel_size_x=0.0, pixel_size_y=0.0, binning_x=1, binning_y=1, expstart=0.0, expend=0.0, bayer_xoffset=0, bayer_yoffset=0, airmass=1.0, focal_length=0.0, flength=0.0, iso_speed=0.0, exposure=0.0, aperture=0.0, ccd_temp=0.0, set_temp=0.0, livetime=0.0, stackcnt=0, cvf=0.0, gain=0, offset=0, focuspos=0, focussz=0, foctemp=0.0, centalt=0.0, centaz=0.0, sitelat=0.0, sitelong=0.0, siteelev=0.0, objctra=None, objctdec=None, ra=None, dec=None, pltsolvd=False, pltsolvd_comment=None)

Bases : object

Python equivalent of Siril fkeywords structure. Contains the FITS header keyword values converted to suitable data types.

classmethod deserialize(data)

Deserialize binary keyword-block (the block produced by keywords_to_py()) into an FKeywords object. Raises ValueError on size mismatch and SirilError for other unpacking issues.

Type renvoyé:

FKeywords

FLEN_VALUE: ClassVar[int] = 71
KEYWORDS_FORMAT: ClassVar[str] = '!71s71s71s71s71s71s71s71s71s71s71s71s71s71s71s71sddQQddddddQQdddddddqqdddddddddQdqqqqdqqdd?'
KEYWORDS_SIZE: ClassVar[int] = 1465
airmass: float = 1.0

Masse d'air au centre du cadre (Gueymard 1993)

aperture: float = 0.0

Valeur de l'ouverture en nombre flottant

bayer_pattern: str = ''

Matrice de Bayer

bayer_xoffset: int = 0

X offset of the Bayer pattern

bayer_yoffset: int = 0

Y offset of the Bayer pattern

binning_x: int = 1

XBINNING FITS header card as an int

binning_y: int = 1

mot clé YBINNING de l'en-tête FITS en int

bscale: float = 1.0

Décalage de la plage de données par rapport à celle d'une valeur non signée (unsigned short)

bzero: float = 0.0

Facteur d'échelle par défaut

ccd_temp: float = 0.0

Température du CCD en nombre à virgule flotante

centalt: float = 0.0

[deg] Altitude du télescope

centaz: float = 0.0

[deg] Azimut du télescope

cvf: float = 0.0

Facteur de conversion (e-/ ADU)

data_max: float = 0.0

used to check if 32b float is in the [0, 1] range

data_min: float = 0.0

used to check if 32b float is in the [0, 1] range

date: datetime | None = None

Date UTC de création du fichier FITS

date_obs: datetime | None = None

ss observation start, UT

Type:

YYYY-MM-DDThh

Type:

mm

dec: float | None = None

Dec en nombre flottant, si disponible

expend: float = 0.0

Fin de l'exposition sous forme de date julienne

exposure: float = 0.0

Temps d'exposition en nombre flottant (s)

expstart: float = 0.0

Début de l'exposition sous forme de date julienne

fhi: float32 = 0.0

MIPS-Hi key in FITS file, "Upper visualization cutoff (float)"

filename: str = ''

Nom de fichier d'origine

filter: str = ''

Nom du filtre actif

flength: float = 0.0

[mm] Longueur focale

flo: float32 = 0.0

MIPS-LO key in FITS file, "Lower visualization cutoff (float)"

focal_length: float = 0.0

[mm] Longueur focale

focname: str = ''

Nom de l'équipement de mise au point

foctemp: float = 0.0

Température du focuseur

focuspos: int = 0

Position du focuseur

focussz: int = 0

[um] Taille du pas du focuseur

gain: int = 0

Facteur de gain lu depuis la caméra

hi: int = 0

MIPS-HI key in FITS file, "Upper visualization cutoff"

image_type: str = ''

Types d'image

instrume: str = ''

Nom de l'instrument

iso_speed: float = 0.0

Valeur de sensibilité ISO sous forme de nombre à virgule flottante

livetime: float = 0.0

Somme des temps d'expositions (s)

lo: int = 0

MIPS-LO key in FITS file, "Lower visualization cutoff"

objctdec: str | None = None

objet Dec sous forme de string, si disponible

objctra: str | None = None

objet Ra sous forme de string, si disponible

object: str = ''

Nom de l'objet d'intérêt

observer: str = ''

Nom de l'observateur

offset: int = 0

Offset value read in camera

pixel_size_x: float = 0.0

mot clé XPIXSZ de l'entête FITS en float

pixel_size_y: float = 0.0

mot clé YPIXSZ de l'entête FITS en float

pltsolvd: bool = False

whether plate solved or not

pltsolvd_comment: str | None = None

plate solution comment

program: str = ''

Logiciel qui a créé ce HDU

ra: float | None = None

Ra en nombre flottant, si disponible

row_order: str = ''

Ordre des lignes dans le tableau d'images

set_temp: float = 0.0

CCD set temperature as a float

siteelev: float = 0.0

[m] Élévation du site d'observation

sitelat: float = 0.0
sitelat_str: str = ''
sitelong: float = 0.0

[deg] Longitude du site d'observation

sitelong_str: str = ''
stackcnt: int = 0

Number of stacked frames

telescop: str = ''

Télescope utilisé pour acquérir cette image

class sirilpy.models.FPoint(x, y)

Bases : object

Represents a 2D point with float x and y coordinate values in the Siril image.

x: float

coordonnée x

y: float

coordonnée y

class sirilpy.models.Homography(h00=0.0, h01=0.0, h02=0.0, h10=0.0, h11=0.0, h12=0.0, h20=0.0, h21=0.0, h22=0.0, pair_matched=0, Inliers=0)

Bases : object

Python equivalent of the Siril Homography structure. Contains coefficients for the Homography matrix that maps a sequence frame onto the reference frame.

Inliers: int = 0

number of inliers kept after RANSAC step

h00: float = 0.0

Matrice d'homographie H00

h01: float = 0.0

Matrice d'homographie H01

h02: float = 0.0

Matrice d'homographie H02

h10: float = 0.0

Matrice d'homographie H10

h11: float = 0.0

Matrice d'homographie H11

h12: float = 0.0

Matrice d'homographie H12

h20: float = 0.0

Matrice d'homographie H20

h21: float = 0.0

Matrice d'homographie H21

h22: float = 0.0

Matrice d'homographie H22

pair_matched: int = 0

nombre de paires trouvées

class sirilpy.models.ImageAnalysis(bgnoise=0.0, fwhm=0.0, wfwhm=0.0, nbstars=0, roundness=0.0, imagetype=0, timestamp=0, channels=0, height=0, width=0, filter='')

Bases : object

Structure to hold image analysis data, used for culling

classmethod deserialize(data)

Unpack a network-safe binary struct into an ImageAnalysis instance.

Type renvoyé:

ImageAnalysis

serialize()

Pack the dataclass into a network-safe binary struct.

Type renvoyé:

bytes

FLEN: ClassVar[int] = 71
bgnoise: float = 0.0

RMS background noise

channels: int = 0

number of channels in the image

filter: str = ''

filter name (fixed-length string from C, max 70 chars)

fwhm: float = 0.0

Moyenne fwhm

height: int = 0

hauteur de l'image

imagetype: ImageType = 0

Image type enum

nbstars: int = 0

Nombre d'étoiles détectées

roundness: float = 0.0

Moyenne de la rondeur des étoiles

timestamp: int = 0

00 UTC)

Type:

UNIX timestamp (64-bit seconds since 1970/1/1 00

wfwhm: float = 0.0

FWHM pondérée moyenne

width: int = 0

largeur de l'image

class sirilpy.models.ImageStats(total=0, ngoodpix=0, mean=0.0, median=0.0, sigma=0.0, avgDev=0.0, mad=0.0, sqrtbwmv=0.0, location=0.0, scale=0.0, min=0.0, max=0.0, normValue=0.0, bgnoise=0.0)

Bases : object

Python equivalent of Siril imstats structure. Contains statistics for a particular channel of a Siril image.

classmethod deserialize(data)

Deserialize binary data into an ImageStats object.

Paramètres:

data (bytes) -- (bytes) Binary data to unpack

Type renvoyé:

ImageStats

Renvoie : un objet ImageStats

Raises: SirilError: If received data size is incorrect

struct.error: If unpacking fails

avgDev: float = 0.0

écart moyen des pixels

bgnoise: float = 0.0

RMS background noise

location: float = 0.0

location of pixel values

mad: float = 0.0

écart moyen des pixels

max: float = 0.0

valeur maximale du pixel

mean: float = 0.0

valeur moyenne des pixels

median: float = 0.0

valeur médiane des pixels

min: float = 0.0

valeur minimale du pixel

ngoodpix: int = 0

nombre de pixels différents de zéro

normValue: float = 0.0

norm value of the pixels

scale: float = 0.0

scale value of the pixels

sigma: float = 0.0

déviation standard des pixels

sqrtbwmv: float = 0.0

square root of the biweight midvariance of pixel values

total: int = 0

nombre total de pixels

class sirilpy.models.ImgData(filenum=0, incl=False, date_obs=None, airmass=0.0, rx=0, ry=0)

Bases : object

Python equivalent of Siril imgdata structure

classmethod deserialize(response)

Deserialize binary response into an ImgData object.

Paramètres:

response (bytes) -- Binary data to unpack.

Renvoie:

An ImgData object with deserialized data.

Type renvoyé:

ImgData

Lève:
  • ValueError -- Si la taille des données reçues est incorrecte.

  • struct.error -- Si la décompression échoue.

airmass: float = 0.0

airmass de l'image

date_obs: datetime | None = None

date de l'observation

filenum: int = 0

real file index in the sequence

incl: bool = False

sélectionné dans la séquence

rx: int = 0

width

ry: int = 0

height

class sirilpy.models.PSFStar(star_name=None, B=0.0, A=0.0, x0=0.0, y0=0.0, sx=0.0, sy=0.0, fwhmx=0.0, fwhmy=0.0, fwhmx_arcsec=0.0, fwhmy_arcsec=0.0, angle=0.0, rmse=0.0, sat=0.0, R=0, has_saturated=False, beta=0.0, profile=StarProfile.GAUSSIAN, xpos=0.0, ypos=0.0, mag=0.0, Bmag=0.0, s_mag=999.99, s_Bmag=999.99, SNR=0.0, phot_is_valid=False, BV=0.0, B_err=0.0, A_err=0.0, x_err=0.0, y_err=0.0, sx_err=0.0, sy_err=0.0, ang_err=0.0, beta_err=0.0, layer=0, units=None, ra=0.0, dec=0.0)

Bases : object

Python equivalent of the Siril fwhm_struct structure. Contains data on a modelled fit to a star identified in the image.

classmethod deserialize(data)

Deserialize a portion of a buffer into a PSFStar object.

Paramètres:

data (bytes) -- (bytes) The full binary buffer containing PSFStar data.

Type renvoyé:

PSFStar

Renvoie:

Objet PSFStar

Lève:
  • ValueError -- If the buffer slice size does not match the expected size.

  • struct.error -- If there is an error unpacking the binary data.

A: float = 0.0

amplitude

A_err: float = 0.0

erreur en A

B: float = 0.0

valeur moyenne du fond du ciel

BV: float = 0.0

only used to pass data in photometric color calibration

B_err: float = 0.0

erreur en B

Bmag: float = 0.0

magnitude B

R: int = 0

Optimized box size to enclose sufficient pixels in the background

SNR: float = 0.0

SNR de l'étoile

ang_err: float = 0.0

erreur sur l'angle

angle: float = 0.0

angle of the x and yaxes with respect to the image x and y axes

beta: float = 0.0

Paramètre beta de l'équation Moffat

beta_err: float = 0.0

erreur en beta

dec: float = 0.0

Déclinaison

fwhmx: float = 0.0

FWHM selon l'axe x en pixels

fwhmx_arcsec: float = 0.0

FWHM sur l'axe x en arc seconds

fwhmy: float = 0.0

FWHM selon l'axe y en pixels

fwhmy_arcsec: float = 0.0

FWHM sur l'axe xyen arc seconds

has_saturated: bool = False

Shows whether the star is saturated or not

layer: int = 0

image channel on which the star modelling was carried out

mag: float = 0.0
  1. magnitude, approximatif ou précis

phot_is_valid: bool = False

True if mag, Bmag, s_mag, s_Bmag and SNR are photometrically accurate with no saturated pixels. Introduced in sirilpy 1.0.4.

profile: StarProfile = 0
ra: float = 0.0

Ascension droite

rmse: float = 0.0

RMSE of the minimization

s_Bmag: float = 999.99

Erreur sur la magnitude B

s_mag: float = 999.99

erreur sur la magnitude (V)

sat: float = 0.0

Niveau au dessus duquel les pixels sont saturés

star_name: str | None = None
sx: float = 0.0

Size of the fitted function on the x axis in PSF coordinates

sx_err: float = 0.0

erreur en sx

sy: float = 0.0

Size of the fitted function on the y axis in PSF coordinates

sy_err: float = 0.0

erreur en sy

units: str | None = None

Unité

x0: float = 0.0

coordonnée x du pic

x_err: float = 0.0

erreur en x

xpos: float = 0.0

x position of the star in the image

y0: float = 0.0

coordonnée y du pic

y_err: float = 0.0

erreur en y

ypos: float = 0.0

y position of the star in the image

class sirilpy.models.Polygon(points, polygon_id=0, color=4294967295, fill=False, legend=None)

Bases : object

Represents a user-defined polygon. These can be filled or outline-only, and can have any color and transparency (alpha) value. They can also have an optional label which is displayed centred on the polygon.

Note that Polygons should be considered transitory if used with the overlay - they can be used to display information to the user but they may be cleared at any time if the user toggles the overlay button in the main Siril interface to clear the overlay.

classmethod deserialize_polygon(data)

Creates a Polygon object by deserializing a byte array.

Renvoie:

A Polygon object and any remaining bytes in the byte

array. (The remaining bytes are for use in deserialize_polygon_list and can be safely ignored if deserializing a single polygon.)

Type renvoyé:

Tuple

Lève:

ValueError -- If there is insufficient data to deserialize.

classmethod deserialize_polygon_list(data)

Creates a List of Polygon objects by deserializing a byte array.

Renvoie:

A List of Polygon objects.

Type renvoyé:

List

Lève:

ValueError -- If there is invalid data to deserialize.

classmethod from_rectangle(rect, **kwargs)

Create a Polygon from a rectangle of the kind returned by sirilpy.connection.get_siril_selection().

Paramètres:
  • rect (Tuple[int, int, int, int]) -- Rectangle tel que (x,y largeur, hauteur)

  • **kwargs -- Additional keyword arguments to pass to Polygon constructor (polygon_id, color, fill, legend)

Renvoie:

A new Polygon instance representing the rectangle

Type renvoyé:

Polygon

contains_point(x, y)

Determine if a point is inside the polygon using Dan Sunday's optimized winding number algorithm.

This algorithm is more robust than ray casting for complex polygons and handles edge cases better, including points on edges and self-intersecting polygons.

Paramètres:
  • x (float) -- X coordinate of the point to test.

  • y (float) -- Y coordinate of the point to test.

Renvoie:

True if the point is inside the polygon, False otherwise.

Type renvoyé:

bool

get_bounds()

Get the bounding box of the polygon.

Renvoie:

(min_x, min_y, max_x, max_y)

Type renvoyé:

Tuple[float, float, float, float]

Lève:

ValueError -- Si le polygone n'a aucun point.

get_max_x()

Get the maximum x coordinate of the polygon.

Type renvoyé:

float

get_max_y()

Get the maximum y coordinate of the polygon.

Type renvoyé:

float

get_min_x()

Get the minimum x coordinate of the polygon.

Type renvoyé:

float

get_min_y()

Get the minimum y coordinate of the polygon.

Type renvoyé:

float

serialize()

Serializes a single Polygon object into a byte array.

Renvoie:

A byte array representing the serialized polygon data.

Type renvoyé:

bytes

Lève:

ValueError -- If the number of points exceeds the allowed limit.

color: int = 4294967295

32-bit RGBA color (packed, uint_8 per component. Default value is 0xFFFFFFFF)

fill: bool = False

whether or not the polygon should be filled when drawn

legend: str = None

une légende optionnelle

points: List[FPoint]

List of points defining the polygon's shape

polygon_id: int = 0

identifiant unique

class sirilpy.models.RegData(fwhm=0.0, weighted_fwhm=0.0, roundness=0.0, quality=0.0, background_lvl=0.0, number_of_stars=0, H=<factory>)

Bases : object

Python equivalent of Siril regdata structure

classmethod deserialize(data)

Deserialize a binary response into a RegData object.

Paramètres:

data (bytes) -- Binary data to unpack

Type renvoyé:

RegData

Returns: RegData object

Raises: SirilError if the received data doesn't match the expected size'

struct.error If unpacking fails

H: Homography

Stores a homography matrix describing the affine transform from this frame to the reference frame

background_lvl: float32 = 0.0

niveau du fond de ciel

fwhm: float = 0.0

copy of fwhm->fwhmx, used as quality indicator

number_of_stars: int = 0

number of stars detected in the image

quality: float = 0.0

mesure de la qualité de l'image

roundness: float32 = 0.0

fwhm->fwhmy / fwhm->fwhmx, 0 when uninit, ]0, 1] when set

weighted_fwhm: float32 = 0.0

used to exclude spurious images

class sirilpy.models.Sequence(seqname='', number=0, selnum=0, fixed=0, nb_layers=-1, rx=0, ry=0, is_variable=False, bitpix=0, reference_image=0, imgparam=None, regparam=None, stats=None, distoparam=None, beg=0, end=0, exposure=0.0, fz=False, type=None, cfa_opened_monochrome=False, current=0)

Bases : object

Python equivalent of Siril sequ structure

beg: int = 0

imgparam[0]->filenum

bitpix: int = 0

image pixel format, from fits

cfa_opened_monochrome: bool = False

CFA SER opened in monochrome mode

current: int = 0

numéro du fichier actuellement chargé

distoparam: List[DistoData] = None

distortion data for the sequence [nb_layers]

end: int = 0

imgparam[number-1]->filenum

exposure: float = 0.0

exposition de l'image

fixed: int = 0

longueur fixe de l'index d'image dans le nom de fichier

fz: bool = False

si le fichier est compressé

imgparam: List[ImgData] = None

a structure for each image of the sequence [number]

is_variable: bool = False

La séquence contient des images de différentes tailles

nb_layers: int = -1

nombre de couches intégrées dans chaque fichier image

number: int = 0

nombres d'images dans la séquence

reference_image: int = 0

image de référence pour l'alignement

regparam: List[List[RegData]] = None

registration parameters for each layer [nb_layers][number]

rx: int = 0

largeur de la première image

ry: int = 0

hauteur de la première image

selnum: int = 0

nombres d'images sélectionné

seqname: str = ''

nom de la séquence

stats: List[List[ImageStats]] = None

statistiques des images pour chaque couche [nb_couche][nombre]

type: SequenceType = None

le type de séquence

Sirilpy Enums

This module provides all the enums that are used within sirilpy.

Enums submodule for Siril. This submodule contains all the enums used within sirilpy.

class sirilpy.enums.BitpixType(value)

Bases : IntEnum

Mimics the Siril bitpix enum. Note that although Siril can handle opening FITS files of any data type, internally it processes images only as USHORT_IMG (uint16) or FLOAT_IMG (float32).

BYTE_IMG = 8
DOUBLE_IMG = -64
FLOAT_IMG = -32
LONG_IMG = 32
SHORT_IMG = 16
USHORT_IMG = 20
class sirilpy.enums.CommandStatus(value)

Bases : IntEnum

Contains Siril command status codes, matching the values returned internally within Siril. These can be used for error handling. CMD_OK and CMD_NO_WAIT are no-error codes; all the other codes represent command errors. These are available through the CommandError exception and may generally be handled without being regarded as fatal to the script.

CMD_ALLOC_ERROR = 1048576
CMD_ARG_ERROR = 32
CMD_DIR_NOT_FOUND = 4194304
CMD_FILE_NOT_FOUND = 131072
CMD_FOR_CFA_IMAGE = 65536
CMD_FOR_PLATE_SOLVED = 262144
CMD_GENERIC_ERROR = 128
CMD_IMAGE_NOT_FOUND = 256
CMD_INVALID_IMAGE = 1024
CMD_LOAD_IMAGE_FIRST = 2048
CMD_NEED_INIT_FIRST = 524288
CMD_NOT_FOR_MONO = 16384
CMD_NOT_FOR_RGB = 32768
CMD_NOT_FOR_SINGLE = 8192
CMD_NOT_FOUND = 1
CMD_NOT_SCRIPTABLE = 8
CMD_NO_CWD = 4
CMD_NO_WAIT = 2
CMD_OK = 0
CMD_ONLY_SINGLE_IMAGE = 4096
CMD_SELECTION_ERROR = 64
CMD_SEQUENCE_NOT_FOUND = 512
CMD_THREAD_RUNNING = 2097152
CMD_WRONG_N_ARG = 16
class sirilpy.enums.DialogID(value)

Bases : IntEnum

classmethod from_name(name)

Safely create from a str containing a potential dialog name (e.g. "ASINH_DIALOG", returning None if the name no longer exists.

Type renvoyé:

DialogID | None

ABERRATION_DIALOG = 19
ABOUT_DIALOG = 0
ANNOTATE_DIALOG = 1
ASINH_DIALOG = 2
ASTROMETRY_DIALOG = 3
BACKGROUND_EXTRACTION_DIALOG = 4
BINXY_DIALOG = 6
CANON_FIXBANDING_DIALOG = 7
CCM_DIALOG = 8
CLAHE_DIALOG = 9
COLOR_CALIBRATION = 10
COMPOSITION_DIALOG = 12
COMPSTARS_DIALOG = 11
COSMETIC_DIALOG = 13
CURVES_DIALOG = 14
CWD_DIALOG = 15
DECONV_DIALOG = 5
DENOISE_DIALOG = 16
DIALOG_FFT = 17
DIALOG_STAR_REMIX = 18
EPF_DIALOG = 20
EXTRACT_CHANNEL_DIALOG = 21
EXTRACT_WAVELETS_LAYERS_DIALOG = 22
FILE_INFORMATION = 23
GHT_DIALOG = 24
HISTOGRAM_DIALOG = 25
ICC_DIALOG = 26
KEYWORDS_DIALOG = 27
LINEARMATCH_DIALOG = 28
MEDIAN_DIALOG = 29
MERGE_CFA_DIALOG = 30
NINA_LIGHT_CURVE = 31
OPEN_DIALOG = 32
PCC_DIALOG = 33
PIXEL_MATH_DIALOG = 34
PREFS_DIALOG = 35
RESAMPLE_DIALOG = 36
RGRADIENT_DIALOG = 37
ROTATION_DIALOG = 38
SATU_DIALOG = 40
SAVEAS_DIALOG = 41
SCNR_DIALOG = 42
SEQLIST_DIALOG = 43
SPLIT_CFA_DIALOG = 44
STARNET_DIALOG = 45
STARS_LIST_WINDOW = 46
STAT_WINDOW = 47
S_PCC_DIALOG = 39
UNPURPLE_DIALOG = 48
WAVELETS_DIALOG = 49
class sirilpy.enums.DialogReq(value)

Bases : IntEnum

Represents the requirements to open a dialog represented by a DialogID

ANY = 1

Image or sequence loaded

IMG = 2

Image loaded

MONO = 3

Mono image loaded

NONE = 4

No requirement, this action works at any time

PLTSOLVD = 5

Image or sequence frame loaded and plate solved

RGB = 6

RGB image loaded

RGBPLTSOLVD = 7

RGB image or sequence frame loaded and plate solved

SEQ = 8

Sequence loaded

class sirilpy.enums.DistoType(value)

Bases : IntEnum

Python equivalent of the Siril disto_source enum

DISTO_FILE = 2

Distorsion provenant d'un fichier fourni

DISTO_FILES = 4

Distortion stored in each file (true only from seq platesolve, even with no distortion, it will be checked upon reloading)

DISTO_FILE_COMET = 5

special for cometary alignement, to be detected by apply reg

DISTO_IMAGE = 1

Distorsion par rapport à l'image actuelle

DISTO_MASTER = 3

Distortion from master files

DISTO_UNDEF = 0

No distortion

class sirilpy.enums.ImageType(value)

Bases : IntEnum

enum representing image functional types

BIAS = 4
DARK = 2
FLAT = 3
LIGHT = 1
UNKNOWN = 0
class sirilpy.enums.LogColor(value)

Bases : IntEnum

Defines colors available for use with SirilInterface.log() For consistency LogColor.Default should be used for normal messages, LogColor.Red should be used for error messages, LogColor.Salmon should be used for warning messages, LogColor.Green should be used for completion notifications, and LogColor.Blue should be used for technical messages such as equations, coefficients etc.

BLUE = 4
DEFAULT = 0
GREEN = 3
RED = 1
SALMON = 2
class sirilpy.enums.PlotType(value)

Bases : IntEnum

Enumeration of available plot types for visualizing data series.

HYPHENS = 2
LINES = 3
LINESHYPHENS = 6
LINESMARKS = 5
LINESPOINTS = 4
MARKS = 1
POINTS = 0
class sirilpy.enums.STFType(value)

Bases : IntEnum

enum representing STF types

ASINH_DISPLAY = 4
AUTOSTRETCH_DISPLAY = 5
HISTEQ_DISPLAY = 6
LINEAR_DISPLAY = 0
LOG_DISPLAY = 1
SQRT_DISPLAY = 2
SQUARED_DISPLAY = 3
class sirilpy.enums.SequenceType(value)

Bases : IntEnum

Python equivalent of the Siril sequence_type enum

SEQ_AVI = 3
SEQ_FITSEQ = 2
SEQ_INTERNAL = 4
SEQ_REGULAR = 0
SEQ_SER = 1
class sirilpy.enums.SirilVport

Bases : object

Defines the Siril viewports

BLUE = 2
GREEN = 1
MONO = 0
RED = 0
RGB = 3
class sirilpy.enums.SlidersMode(value)

Bases : IntEnum

MINMAX = 1
MIPSLOHI = 0
USER = 2
class sirilpy.enums.StarProfile(value)

Bases : IntEnum

Python equivalent of the Siril starprofile enum. Used to identify the type of fit used to model a star in the image. Note that MOFFAT_FIXED is currently not used in Siril, but is reserved for future use for Moffat stars modelled with a fixed beta parameter

GAUSSIAN = 0
MOFFAT = 1
MOFFAT_FIXED = 2

Sirilpy Plotting

This submodule provides classes and method to access the native Siril plotting functionality. Of course, you can also use matplotlib but this submodule provides access to the same plotting capabilities as used internally within Siril for a more seamless result. All its members are made available at the module root level, there is no need to import models separately.

Once populated, the PlotData object can be plotted using SirilInterface.xy_plot().

Plot submodule for Siril, providing classes for plot data representation and serialization. This submodule enables users to create and configure various types of plots with customizable appearance and error bars.

class sirilpy.plot.PlotData(title='Data Plot', xlabel='X', ylabel='Y', savename='plot', show_legend=True, datamin=None, datamax=None)

Bases : object

Metadata container for plot configuration. The actual series data are held in SeriesData objects and can be added using the Class methods add_series or add_series_obj after initialization of the PlotData.

Membres :

title: Plot title xlabel: X-axis label ylabel: Y-axis label savename: Save filename (extension is added automatically) show_legend: bool indicating whether to show legend datamin: List [xmin, ymin] forcing the bottom left coordinate to show. If omitted, the range is set to the data range. datamax: List [xmax, ymax] forcing the top right coordinate to show. If omitted, the range is set to the data range.

classmethod serialize(plot_data)

Serialize plot data for shared memory transfer using network byte order.

Paramètres:

plot_data (PlotData) -- PlotData object containing plot configuration

Type renvoyé:

Tuple[bytes, int]

Renvoie:

Tuple of serialized bytes and total length

add_series(x_coords, y_coords, label=None, plot_type=PlotType.LINES, n_error=None, p_error=None)

Add a new series to the plot metadata.

Renvoie:

the created SeriesData object for further manipulation if needed.

Type renvoyé:

SeriesData

add_series_obj(series)

Add a pre-created SeriesData object to the plot metadata.

Retourne : None

Type renvoyé:

None

class sirilpy.plot.SeriesData(x_coords, y_coords, label=None, plot_type=PlotType.LINES, n_error=None, p_error=None)

Bases : object

Represents a single data series for plotting.

Membres :

x_coords: Either a List[float] or a np.ndarray containing the values for the x coordinates for this series

y_coords: Either a List[float] or a np.ndarray containing the values for the y coordinates for this series

label: A str containing a label for the series (shown in the plot legend)

plot_type: a PlotType setting the type of marks to use

n_error: Either a List[float] or a np.ndarray containing values for the y-axis negative errors for this series

p_error: Either a List[float] or a np.ndarray containing values for the y-axis positive errors for this series

Sirilpy Utility Methods

This submodule provides utility methods for use in Siril python scripts. The most important is ensure_installed() but there are also methods such as download_with_progress() which provides a highly robust method for downloading large files with good error recovery through a retries and resume mechanism.

Utility module for Siril Python interface providing helper functions for file operations, package management, and standard I/O control to support Siril's scripting capabilities.

class sirilpy.utility.SuppressedStderr

Bases : object

This context manager allows suppression of the script's stderr, which can be useful if you are using module functions that are known to produce warnings that you want to avoid distracting the user with, such as FutureWarnings of features that have become deprecated but are in a dependency rather than your own code. The class should be used sparingly and should not be used to hide evidence of bad code.

class sirilpy.utility.SuppressedStdout

Bases : object

This context manager allows suppression of the script's stdout, which can be useful to avoid flooding the log with stdout messages from an excessively verbose module used in the script.

Exemple

import sirilpy as s
siril = s.SirilInterface()
print("This message will appear in the Siril log")
with s.SuppressedStdout():
    print("This message will not appear")
print("This message will appear again")
sirilpy.utility.check_module_version(requires=None)

Check the version of the Siril module is sufficient to support the script. This is not mandatory if you are only using classes, methods etc. that are provided in the initial public release, but if you rely on methods that are noted int he API documentation as having been added at a particular version of the module then you must check the running sirilpy module supports your script by calling this function.

Siril will not show scripts with unsatisfied check_module_version() calls in the repository list in 'Get Scripts', so if you want a function that enables different code paths for different versions you should use needs_module_version() instead.

Paramètres:

requires (str) -- A version format specifier string following the same format used by pip, i.e. it may contain '==1.2', '!=3.4', '>5.6', '>=7.8', or a combination such as '>=1.2,<3.4'

Renvoie:

True if requires = None or if the available sirilpy module version satisfies the version specifier, otherwise False

Lève:

ValueError -- if requires is an invalid version specifier.

sirilpy.utility.download_with_progress(siril, url, file_path, max_retries=3, retry_delay=5, resume=True)

Robust file download method with native Siril progress tracking and error handling using retries and a resume mechanism.

Type renvoyé:

bool

sirilpy.utility.ensure_installed(*packages, version_constraints=None, reinstall=False)

Ensures that the specified package(s) are installed and meet optional version constraints.

Paramètres:
  • *packages (str or List[str]) -- Name(s) of the package(s) to ensure are installed.

  • version_constraints (str or List[str], optional) -- Version constraint string(s) (e.g. ">=1.5", "==2.0"). Can be a single constraint or a list matching packages.

  • reinstall (bool, optional) -- Forces reinstallation. Defaults to False.

Renvoie:

Vrai si tous les paquets sont installés avec succès ou répondent déjà aux contraintes.

Type renvoyé:

bool

Lève:
  • SirilError -- Si l'installation du paquet échoue.

  • ValueError -- Si le nombre de contraintes diffère du nombre de paquets à installer.

  • TimeoutError -- Si pip échoue avec un délai d'attente apparent.

  • SystemExit -- If a package that is already imported needs to be reinstalled with a different version.

sirilpy.utility.human_readable_size(bytes_size)

Convertir les bytes en un format lisible par l'homme.

Paramètres:

bytes_size (int) -- Taille en bytes

Renvoie:

Taille formatée avec l'unité appropriée (B, KB, MB, GB, TB)

Type renvoyé:

str

Lève:

TypeError -- sur un type d'entrée incorrect

sirilpy.utility.needs_module_version(requires=None)

Check the version of the Siril module is sufficient to support a feature. This allows writing optional code paths for different sirilpy API levels. The function works the same as check_module_version() but the presence of an unsatisfied needs_module_version() call will not prevent a script from showing up in the list in 'Get Scripts'

Paramètres:

requires (str) -- A version format specifier string following the same format used by pip, i.e. it may contain '==1.2', '!=3.4', '>5.6', '>=7.8', or a combination such as '>=1.2,<3.4'

Renvoie:

True if requires = None or if the available sirilpy module version satisfies the version specifier, otherwise False

Lève:

ValueError -- if requires is an invalid version specifier.

sirilpy.utility.parse_fits_header(header_text, include_comments=False)

Parse FITS header from text content into a dictionary with support for HIERARCH and CONTINUE keywords.

Handles Siril's newline-separated FITS header format and converts it to a dictionary compatible with astropy.wcs.WCS. Supports extended FITS keywords via HIERARCH and long string values via CONTINUE.

Paramètres:
  • header_text (str) -- Raw header string with header cards separated by newlines. Expected format: "KEYWORD = value / comment"

  • include_comments (bool) -- If True, includes COMMENT and HISTORY cards in the output. If False (default), these cards are skipped.

Type renvoyé:

Dict[str, Union[str, int, float, bool]]

Renvoie:

Dictionary mapping FITS header keywords (str) to their parsed values. Values are converted to appropriate Python types: - 'T'/'F' -> bool - Quoted strings -> str (quotes removed, with CONTINUE support for long strings) - Numeric strings -> int or float - Everything else -> str - COMMENT/HISTORY cards -> str (content after keyword, if include_comments=True) - HIERARCH keywords -> str (full hierarchical keyword preserved)

Notes

  • Filters out warning messages, tracebacks, and other non-header content

  • By default ignores COMMENT and HISTORY cards (set include_comments=True to include)

  • Skips malformed cards or invalid keywords

  • Standard keywords must be ≤8 characters and alphanumeric (plus underscore/hyphen)

  • HIERARCH keywords can be longer and contain spaces/dots

  • CONTINUE cards are automatically merged with the previous string value

  • Comments after '/' are ignored for regular cards

Exemple

>>> header_str = '''SIMPLE  = T / file conforms to FITS standard
... BITPIX  = -32 / bits per pixel
... HIERARCH ESO DET CHIP1 NAME = 'CCD #1' / detector name
... LONGSTR = 'This is a very long string that needs to be '
... CONTINUE  'continued on the next line'
... COMMENT Test comment'''
>>> result = parse_fits_header(header_str)
>>> result['SIMPLE']
True
>>> result['BITPIX']
-32
>>> result['HIERARCH ESO DET CHIP1 NAME']
'CCD #1'
>>> result['LONGSTR']
'This is a very long string that needs to be continued on the next line'
sirilpy.utility.safe_subprocess_Popen(command, **kwargs)

Provides a safe alternative to subprocess.Popen, accounting for the fact that a subprocess command line may be run from a flatpak environment and require use of flatpak-spawn to ensure it runs outside the sandbox, avoiding issues with subprocesses that rely on environment variables and so on. safe_subprocess_Popen is a drop-in replacement for subprocess.Popen for use in Siril scripts.

Introduced in sirilpy version 1.0.3

sirilpy.utility.safe_subprocess_run(command, **kwargs)

Provides a safe alternative to subprocess.Popen, accounting for the fact that a subprocess command line may be run from a flatpak environment and require use of flatpak-spawn to ensure it runs outside the sandbox, avoiding issues with subprocesses that rely on environment variables and so on. safe_subprocess_run is a drop-in replacement for subprocess.run for use in Siril scripts.

Introduced in sirilpy version 1.0.3

sirilpy.utility.truncate_utf8(data, max_bytes)

Tronque l'entrée utf8. Accepte soit des octets, soit des chaînes de caractères en entrée et renvoie les données dans le même format que l'entrée.

Paramètres:

data (bytes or str) -- Les données à tronquer

Renvoie:

Les données tronquées

Type renvoyé:

bytes or str

Lève:

TypeError -- si l'entrée n'est pas de type bytes ou str

sirilpy.utility.uninstall_package(package_name)

Uninstall a package using pip, streaming output to stdout. Introduced in sirilpy 1.0.15.

Paramètres:

package_name (str) -- Name of the package to uninstall.

Lève:

subprocess.CalledProcessError -- Si la désinstallation avec pip échoue.

Sirilpy GPU Helpers

This submodule provides helper classes to make it easier to manage GPU framework packages such as ONNX, Torch etc. for use in Siril python scripts. The landscape of these frameworks' support for different GPU architectures on different OSes is rapidly developing and the helpers aim to suggest reliable packages / configurations. This means that the proposed configurations may in some cases be conservative: the aim is to provide a good and robust level of GPU support for as many users as possible in an automated python environment rather than the absolute best, but perhaps fragile, optimisation.

GPU helper module for Siril Python interface providing helper functions for detection, installation and testing of GPU-related modules. Initial scope is ONNX, torch and jax

class sirilpy.gpuhelper.JaxHelper

Bases : object

Une classe d'aide pour détecter, installer et tester JAX avec l'accélération matérielle appropriée.

Cette classe détecte automatiquement la configuration du système et installe la variante JAX appropriée (CPU, CUDA, ROCm, etc.) en fonction du matériel disponible.

ensure_jax()

Wrapper for install_jax() that only installs it if needed, with negligible overhead if it is already installed.

Type renvoyé:

bool

Determine the recommended JAX backend and installation parameters. When multiple GPUs are present, uses priority system to choose the best one.

JAX has limited platform support: - NVIDIA: CUDA on Linux (Windows support experimental/limited) - AMD ROCm: Linux only - Apple Silicon: Metal backend - Intel: Experimental plugin with dependency issues

Type renvoyé:

Dict[str, Any]

Renvoie:

Dict with 'backend', 'packages', 'extra_index_url' keys

install_jax(force_variant=None, version_constraint=None, force_reinstall=False)

Install JAX with the appropriate variant for the detected hardware. Use this instead of ensure_installed() to ensure that jax is installed correctly for the given hardware / OS

Paramètres:
  • force_variant (Optional[str]) -- Override auto-detection with specific variant (e.g., 'jax[cpu]')

  • version_constraint (Optional[str]) -- Chaîne de contrainte de version (par exemple, '>=0.4.0')

force_reinstall : Force une réinstallation

Renvoie:

True if installation succeeded, False otherwise

Type renvoyé:

bool

is_jax_installed()

Vérifie si PyTorch est installé sans l'importer.

Type renvoyé:

bool

status()

Prints the current status of the Jax Helper class in regard to its support for different OSes, GPUs. The world of heterogenous computing is developing rapidly and while support for some of the frameworks for which helpers are available is not yet universally available, hopefully it will improve in the future.

test_jax()

Test JAX functionality and return execution provider.

Renvoie:

the bool returned is True if jax works or False if it does not, and the str is "gpu" if JAX is using GPU, "cpu" if using CPU or None if

Type renvoyé:

Tuple[bool,str]

Lève:
  • RuntimeError -- Si le calcul JAX échoue ou si la vérification de précision échoue

  • ImportError -- Si JAX n'est pas installé

uninstall_jax(dry_run=False)

Detect and uninstall any existing JAX-related packages.

This is useful when you need to clean up a problematic JAX installation before installing a different variant (e.g., falling back from GPU to CPU).

Paramètres:

dry_run (bool) -- Si True, détecter uniquement les paquets sans les désinstaller

Type renvoyé:

Dict[str, Any]

Renvoie:

Dictionnaire contenant des informations sur les paquets détectés et désinstallés

class sirilpy.gpuhelper.ONNXHelper

Bases : object

A class to handle detection and installation of the appropriate ONNX Runtime package based on the system hardware and configuration.

Example usage (this should be used instead of sirilpy.ensure_installed("onnxruntime") to install the correct package for the user's system.)

oh = sirilpy.ONNXHelper()
oh.ensure_onnxruntime()
ensure_onnxruntime()

Wrapper for install_onnxruntime() that only installs it if needed, with negligible overhead if it is already installed.

Type renvoyé:

bool

get_execution_providers_ordered(ai_gpu_acceleration=True, force_check=False)

Get execution providers ordered by priority. This function returns a list of available ONNX Runtime execution providers in a reasonable order of priority, covering major GPU platforms: The CPU provider is always included as the final fallback option.

Paramètres:
  • ai_gpu_acceleration (bool) -- Whether to include GPU acceleration providers. Defaults to True.

  • force_check (bool) -- Whether to force re-checking even if a cached config exists. Defaults to False.

Renvoie:

Liste triée des fournisseurs d'exécution disponibles.

Type renvoyé:

list

Determine the recommended ONNX Runtime backend based on hardware. When multiple GPUs are present, uses priority system to choose the best one.

Note: ONNX Runtime has platform-specific backend support: - Windows: DirectML for all GPUs (NVIDIA, AMD, Intel) - more reliable, no driver dependencies - Linux: CUDA for NVIDIA, CPU for AMD (no ROCm support yet), OpenVINO for Intel

Renvoie:

'gpu', 'directml', 'openvino', 'coreml', or 'cpu'

Type renvoyé:

Backend name

import_onnxruntime()

Import onnxruntime, add it to the global dict, test if it's built against CUDA and if so preload the CUDA and CUDNN libraries to improve the chances of finding them if Torch[CUDA] happens to be installed.

install_onnxruntime(force=False)

Detect system configuration and install the appropriate ONNX Runtime package.

Paramètres:

force -- bool: If True, force reinstallation even if onnxruntime is already installed.

Renvoie:

True if installation was successful or already installed, False otherwise.

Type renvoyé:

bool

Lève:

TimooutError -- if a TimeoutError occurs in ensure_installed() - this avoids falling back to the CPU-only package purely because of network issues

is_onnxruntime_installed()

Check if any onnxruntime package is already installed and usable.

Renvoie:

(is_installed, package_name) where package_name could be

'onnxruntime', 'onnxruntime-gpu', 'onnxruntime-silicon', etc.

Type renvoyé:

tuple

run(session, model_path, output_names, input_feed, run_options=None, return_first_output=False)

Run inference with automatic CPU fallback if the session fails.

Paramètres:
  • session -- The ONNX runtime inference session

  • model_path (str) -- Path to the ONNX model file (needed for CPU fallback)

  • output_names -- Names of the outputs to compute, or None for all outputs

  • input_feed -- Dictionary mapping input names to input tensors

  • run_options -- Optional run options for the inference session

  • return_first_output (bool) -- If True, return only the first output instead of the full list

Renvoie:

(result, session) where result is the inference output (or first output if return_first_output=True) and

session is the (potentially updated) inference session

Type renvoyé:

tuple

status()

Prints the current status of the ONNX Helper class in regard to its support for different OSes, GPUs. The world of heterogenous computing is developing rapidly and while support for some of the frameworks for which helpers are available is not yet universally available, hopefully it will improve in the future.

test_onnxruntime(ort=None)

Tester un fichier onnxruntime importé.

Args:install_torch(cuda_version=cuda_version)
ort: The ONNX runtime module to test. If None, the method will

attempt to import onnxruntime for the test.

Renvoie:

a list of confirmed working ONNXRuntime ExecutionProviders in priority order

Type renvoyé:

list

uninstall_onnxruntime()

Detects and uninstalls all variants of onnxruntime packages. Checks for any package starting with 'onnxruntime'.

Renvoie:

A list of uninstalled packages

Type renvoyé:

list

class sirilpy.gpuhelper.TorchHelper

Bases : object

Helper class for PyTorch detection, installation and testing.

ensure_torch(cuda_version=None)

Ensure PyTorch is installed with the appropriate backend.

Paramètres:

cuda_version (Optional[str]) -- Optional CUDA version to override auto-detection (e.g., 'cu118', 'cu126', 'cu128')

Type renvoyé:

bool

Returns: True on success, False on failure

Determine the recommended PyTorch backend and installation parameters. When multiple GPUs are present, uses priority system to choose the best one.

PyTorch has good cross-platform support: - NVIDIA: CUDA on all platforms - AMD ROCm-compatible: ROCm on Linux AND Windows - Intel Arc: XPU backend - Apple Silicon: MPS backend

Type renvoyé:

Dict[str, Any]

Renvoie:

Dict with 'backend', 'cuda_version', 'extra_index_url', 'packages' keys

get_torch_device(use_gpu=True)

Obtains a suitable torch device based on the capabilities of the installed torch package. if use_gpu is False, torch.device("cpu") will be returned. This function is available since sirilpy 1.0.17

Type renvoyé:

torch.device

install_torch(cuda_version=None, extra_index_url=None, packages=None)

Install PyTorch with specified configuration.

Paramètres:
  • cuda_version (Optional[str]) -- CUDA version (e.g., 'cu118', 'cu126', 'cu128')

  • extra_index_url (Optional[str]) -- PyTorch wheel repository URL

  • packages (Optional[list]) -- List of packages to install

is_torch_installed()

Vérifie si PyTorch est installé sans l'importer.

Type renvoyé:

bool

status()

Prints the current status of the Torch Helper class in regard to its support for different OSes, GPUs. The world of heterogenous computing is developing rapidly and while support for some of the frameworks for which helpers are available is not yet universally available, hopefully it will improve in the future.

test_torch()

Run tests to verify that torch is installed and runs correctly.

uninstall_torch()

Detects and uninstalls PyTorch and related packages. Checks for torch ecosystem packages. :returns: A list of uninstalled packages :rtype: list

sirilpy.gpuhelper.detect_gpu_capabilities()

Comprehensive GPU detection for all supported hardware.

Type renvoyé:

Dict[str, Any]

Renvoie:

Dict containing detected hardware information and recommendations for PyTorch, ONNX, and JAX backends.

sirilpy.gpuhelper.get_gpu_detection_report()

Generate a comprehensive GPU detection report suitable for display in a GUI.

Type renvoyé:

Dict[str, Any]

Renvoie:

Dict containing all detected hardware and recommended configurations for ONNX, PyTorch, and JAX, including GPU priority information.

Sirilpy TK GUI

Avertissement

This submodule is now deprecated. There are no longer any scripts in the repository that use tksiril and submissions to the siril-scripts repository will no longer be accepted if they use tksiril. You should migrate any personal scripts to use PyQt6 instead. The tksiril submodule will be removed in a future version of Siril.

This submodule provides some helper functions to support consistent GUI implementation using tkinter. It must be explicitly imported in order to be used. Note that when writing TKinter GUIs you should import ThemedTK from the ttkthemes module, because the bare TKinter UI shows up poorly on MacOS. ThemedTK and the methods available in the tksiril module help to provide a consistent look for Siril script GUIs on all platforms.

Avertissement

Linux users running a Wayland desktop should note that Tkinter does not yet have support for pure Wayland. In order to use python scripts utilising Tkinter GUIs you must have the XWayland compatibility package installed. If you don't, you will see errors about DISPLAY being unavailable.

from sirilpy import tksiril

TKsiril submodule for Siril, providing utility methods to achieve consistent script GUI appearance using the TKinter toolkit.

DEPRECATION WARNING: the tksiril submodule is deprecated from Siril 1.4.3. It will remain part of sirilpy throughout the stable 1.4 series but has been removed from master and will therefore disappear with the release of Siril 1.6.0.

No new scripts will be accepted in the siril-scripts repository if they use the tksiril submodule.

class sirilpy.tksiril.ScrollableFrame(container, *args, **kwargs)

Bases : Frame

A scrollable frame widget that can contain other widgets.

This class creates a frame with vertical scrolling capability using a Canvas widget and Scrollbar. It supports both scrollbar and mouse wheel scrolling across all platforms (Windows, Mac, Linux).

Utilisation :

scrollable = ScrollableFrame(parent) scrollable.pack(fill="both", expand=True)

# Add widgets to scrollable.scrollable_frame label = ttk.Label(scrollable.scrollable_frame, text="Hello") label.pack()

# Optionally bind mouse wheel to child widgets scrollable.add_mousewheel_binding(label)

add_mousewheel_binding(widget=None)

Add mouse wheel scrolling support to a widget and its children.

This method recursively binds mouse wheel events to the specified widget and all its child widgets. It uses platform detection to apply the appropriate event bindings for each operating system.

Paramètres:

widget -- The tkinter widget to bind mouse wheel events to. The binding will be applied recursively to all children. If no widget is specified it will default to the ScrollableFrame itself.

Exemple

# Add a complex widget to the scrollable frame frame = ttk.Frame(scrollable.scrollable_frame) label = ttk.Label(frame, text="Hello") button = ttk.Button(frame, text="Click me")

# Bind mouse wheel to the entire widget hierarchy scrollable.add_mousewheel_binding(frame)

sirilpy.tksiril.create_tooltip(widget, text, wrap_length=250)

Create a tooltip for a given Tkinter widget.

Paramètres:
  • widget (tk.Widget) -- The widget to attach the tooltip to

  • text (str) -- The tooltip text to display

  • max_width (int, optional) -- Maximum width of the tooltip. Defaults to 300.

  • wrap_length (int, optional) -- Length at which text wraps. Defaults to 250.

Lève:

TypeError -- If text is not a string or the provided widget is not a valid Tkinter widget

sirilpy.tksiril.elevate(root)

Raises the Tk root window to the top of the window stack. Useful after calls to sirilpy methods that present child windows of the main Siril window such as info_messagebox().

NOTE: For this to work on KDE desktops, focus-stealing prevention must be disabled.

sirilpy.tksiril.match_theme_to_siril(themed_tk, s, on_top=False)

Match the Tkinter theme to the Siril configuration and set the script dialog to have topmost status, meaning that it will remain in front of other non-topmost windows.

Paramètres:
  • s (SirilInterface) -- sirilpy.SirilInterface class to provide the Siril theme (light or dark) to match

  • themed_tk (ThemedTk) -- ThemedTk instance to apply the theme to

  • on_top -- whether the script window should be always on top of other windows

Lève:
  • TypeError -- Si les arguments de l'entrée ne sont pas du bon type

  • ValueError -- If the theme configuration is not 0 or 1

  • AttributeError -- Si les méthodes requises ne sont pas disponibles

  • RuntimeError -- Si des erreurs surviennent lors de l'installation ou de la configuration du thème

sirilpy.tksiril.standard_style()

Provide a standardised ttk style to allow consistent visual appearance between different Siril python scripts.

Paramètres:

none

Lève:

SirilError -- Si la création ou la configuration du style échoue

Sirilpy Tkfilebrowser

Avertissement

This submodule is now deprecated. There are no longer any scripts in the repository that use tkfilebrowser and submissions to the siril-scripts repository will no longer be accepted if they use tkfilebrowser. You should migrate any personal scripts to use PyQt6 instead. The tkfilebrowser submodule will be removed in a future version of Siril.

This submodule is a fork of tkfilebrowser. The fork addresses a bug in the original code where duplicate device entries could cause errors in generating the filebrowser, and ensures the code can be mantained as the upstream package was last updated several years ago.

Documentation for tkfilebrowser can be found here. Note that some compatibility improvements have been made in the version included in sirilpy:

  • sirilpy.tkfilebrowser.askdirectory() has been added as an alias for tkfilebrowser.askopendirname() to maintain compatibility with tk.filedialog.askdirectory().

  • In filefilter specifications tkfilebrowser requires multiple extensions to be provided separated by | whereas filedialog requires space-separated extensions: sirilpy.tkfilebrowser has been adapted to accept either format.

This submodule serves the sole purpose of being a drop-in replacement for the standard Tk filedialog on Linux, as the standard Tk filedialog is horrible on Linux. It can be used as a replacement like this:

if sys.platform.startswith("linux"):
    import sirilpy.tkfilebrowser as filedialog
else:
    from tkinter import filedialog

Sirilpy Exceptions

This submodule provides some customized exceptions to support Siril-specific error handling. All its members are made available at the module root level, there is no need to import it separately.

The sirilpy exceptions policy is as follows:

  • At a low level within sirilpy methods a variety of exception types may be raised (those shown below as well as exceptions raised from other modules such as struct.error). Internal exception types are all descended from SirilError and may therefore be caught using except SirilError. Other exception types are re-raised as a SirilError to show the method where they were generated, but the underlying error can still be seen either in a traceback or using the Exception __cause__ property.

  • Some error types are recoverable errors such as NoImageError, NoSequenceError and CommandError. These exception types can be handled at script level (for example by showing a warning dialog reminding the user to load an image).

  • Other error types are typically not recoverable, such as SharedMemoryError or SirilConnectionError.

Exceptions submodule for Siril, providing exception classes for use in exception raising within the sirilpy module.

exception sirilpy.exceptions.CommandError(message='Command execution failed', status_code=CommandStatus.CMD_GENERIC_ERROR)

Bases : SirilError

Raised when a command sent to Siril fails to execute properly. (Note: 'command' in this case refers to internal commands sent from the python module to the Siril python handler, not Siril commands of the type that might be entered in the Siril command entry.) The full set of command status codes is shown in the CommandStatus enum. These exceptions are often recoverable and should therefore be handled before generically handling other SirilError types that are considered fatal.

status_code

(CommandStatus) Indicates the status code returned by the Siril command. This may be used in error handlers to allow scripts to handle some types of command error and continue (e.g. by prompting a user intervention).

exception sirilpy.exceptions.DataError(message='Error handling data')

Bases : SirilError

Raised when there are problems with data handling. This includes cases like:

  • Données d'image invalides

  • Erreurs de conversion des données

  • Échecs d'allocation de mémoire

  • Débordements du buffer

exception sirilpy.exceptions.ImageDialogOpenError(message='Siril image dialog is open')

Bases : SirilError

Exception raised when an image processing dialog is open.

exception sirilpy.exceptions.MouseModeError(message='Siril mouse mode error')

Bases : SirilError

Exception raised when Siril is in the wrong mouse mode.

exception sirilpy.exceptions.NoImageError(message='No Siril image loaded')

Bases : SirilError

Raised when a method requires an image to be loaded but no image is loaded. These exceptions are often recoverable and should therefore be handled before generically handling other SirilError types that are considered fatal.

exception sirilpy.exceptions.NoSequenceError(message='No Siril sequence loaded')

Bases : SirilError

Raised when a method requires a sequence to be loaded but no sequence is loaded. These exceptions are often recoverable and should therefore be handled before generically handling other SirilError types that are considered fatal.

exception sirilpy.exceptions.ProcessingThreadBusyError(message='Siril processing thread is busy')

Bases : SirilError

Exception raised when the processing thread is already in use.

exception sirilpy.exceptions.SharedMemoryError(message='Siril shared memory error')

Bases : SirilError

Raised when there are problems connecting to or communicating with Siril using shared memory.

SharedMemoryError is not raised directly but will be wrapped in a SirilError. It should generally be regarded as fatal and the script should shut down gracefully if possible or just stop.

exception sirilpy.exceptions.SirilConnectionError(message='Failed to connect to Siril')

Bases : SirilError

Raised when there are problems connecting to or communicating with Siril. This includes cases like:

  • Siril n'est pas en fonctionnement

  • Échecs de connexion au socket

  • Erreurs de protocole de communication

  • Déconnexions inattendues

SirilConnectionError is not raised directly but will be wrapped in a SirilError. It should generally be regarded as fatal and the script should shut down gracefully if possible or just stop.

exception sirilpy.exceptions.SirilError(message='An error occurred')

Bases : Exception

Base exception class for all Siril-related errors.

All other Siril exceptions inherit from this class, making it easy to catch any Siril-related error with a single except clause.