Справочник по программному интерфейсу (API) модуля Sirilpy 0.7.41 языка Python
Модуль sirilpy языка Python поддерживает взаимодействие с запущенным экземпляром Siril. Он может запрашивать представления текущего загруженного изображения вместе с его метаданными, включая информацию о детектированных звездах, а также текущую загруженную последовательность и большинство метаданных кадров.
Данная документация сгенерирована автоматически из кода python-модуля версии 0.7.41.
Он также может выполнять команды Siril с помощью метода SirilInterface.cmd()
, и его целью является предоставление надежного интерфейса для написания продвинутых скриптов для Siril, которые невозможно реализовать с использованием предыдущих простых файлов сценариев.
Например, теперь скрипты могут иметь графические интерфейсы на базе TKinter с использованием модулей tkinter и ttkthemes, а также они могут использовать множество модулей из экосистемы Python, включая numpy, scipy, pillow и многие другие.
Примечание
Существуют некоторые ограничения относительно модулей, которым для работы требуется установка системных бинарных пакетов.
В первоначальном выпуске модуля большинство методов, связанных с изображением или последовательностью, загруженными в Siril, доступны только для чтения. Цель заключается в том, чтобы параметры загруженного изображения или последовательности могли быть получены и использованы в качестве входных данных для сценариев, например, для вычислений или ввода условий, но в большинстве случаев для работы с загруженным изображением следует использовать существующий набор команд Siril. Таким образом, ключевые слова заголовка можно задать с помощью cmd("update_key", "ключ", "значение")
, а большинство встроенных операций с изображениями можно выполнить с помощью соответствующей команды Siril. Основным исключением из правила методов python, предоставляющих доступ только для чтения, является метод set_image_pixeldata()
, который позволяет устанавливать пиксельные данные в загруженном изображении из массива numpy. Это означает, что с помощью python можно добавлять новые алгоритмы обработки пикселей, изначально получая пиксельные данные из загруженного изображения с помощью get_image_pixeldata()
и устанавливая их по завершении с помощью set_image_pixeldata()
. Аналогичные функции доступны для получения и настройки пиксельных данных из кадров последовательности.
Зависимости
Модуль sirilpy зависит от:
numpy >= 1.20.0
packaging >= 21.0
pywin32 >= 300 (only on Windows)
Руководство по написанию скриптов Siril
В отличие от большинства сред Python, скрипты Siril запускаются непосредственно из самой программы Siril, и обычный пользователь обычно не знает, как получить доступ или как использовать виртуальное окружение Python за пределами Siril. Это означает, что некоторые задачи, которые довольно тривиальны в типичных сценариях Python, такие как установка пакетов, становятся более сложными. Нельзя ожидать, что пользователь будет получать доступ к командной строке и устанавливать пакеты самостоятельно с помощью команды
python3 -m pip install
.Поэтому модуль предоставляет метод
ensure_installed()
. Этот метод использует pip для того чтобы убедиться, что необходимые модули установлены и могут быть импортированы.
Скрипты Siril всегда должны содержать имя автора, информацию о правах на копирование / лицензионные сведения и контактные данные, такие как канал YouTube, веб-сайт или форум, где с ним можно связаться по вопросам, связанным со скриптом. Это является рекомендацией для независимо распространяемых скриптов и обязательным требованием для всех скриптов, отправляемых в репозиторий скриптов. Если вы пишете скрипт, вы несете ответственность за его поддержку.
По мере роста репозитория и развития API не все опубликованные скрипты обязательно будут совместимы со всеми версиями Siril, которые будут использоваться:
Если ваш скрипт использует команды Siril, вы должны использовать команду
requires
. Её можно вызвать непосредственно в файле скрипта Siril, либо её можно вызвать из Python-скрипта с помощьюSirilInterface.cmd("requires", "min_version", {"max_version"})
(параметр max_version является необязательным), но ее можно использовать для того, чтобы скрипты, разработанные для старых версий Siril, больше не отображались как применимые к новым версиям, если синтаксис команды изменился.Если ваш скрипт использует какие-либо функции python-модуля Siril, добавленные после первоначального выпуска, вам следует вызвать метод
sirilpy.check_module_version()
, чтобы убедиться, что установленная версия соответствует требованиям вашего скрипта. Версии, в которых были добавлены функции, будут перечислены в документации API для всех функций, добавленных после первоначального публичного выпуска.Код, заполняющий представление репозитория скриптов Siril, автоматически будет фильтровать скрипты, чьи требования к версии Siril или версии модуля Python не соблюдаются.
Если в модуль после начального публичного релиза будут добавлены новые классы или методы, версия, в которой они были введены, будет отмечена в строке документации и в онлайн-документации, сгенерированной на её основе.
Siril нацелен на работу под Linux, Windows и MacOS. Авторам скриптов рекомендуется, где это возможно, гарантировать, что их скрипты будут работать правильно на всех трех ОС.
Sirilpy Connection
Этот подмодуль предоставляет основной класс SirilInterface, используемый для обмена данными между Siril и python-скриптом. Все его элементы доступны на корневом уровне модуля, поэтому нет необходимости импортировать подключение отдельно.
Модуль подключения для Siril предоставляет возможность подключаться к запущенному экземпляру Siril и взаимодействовать с ним. Включает широкий спектр методов, которые можно использовать для получения и установки данных из/в Siril.
- class sirilpy.connection.SirilInterface
Базовые классы:
object
SirilInterface — это основной класс, предоставляющий интерфейс для запущенного экземпляра Siril и доступ к методам для взаимодействия с ним через встроенную систему команд Siril, а также доступ к данным изображений и последовательностей.
- clear_image_bgsamples()
Clears all background sample points from the image.
- cmd(*args)
Отправляет команду в Siril для выполнения. Перечень доступных команд можно найти в онлайн-документации. Команда и её аргументы предоставляются в виде списка строк.
- Параметры:
*args (
str
) -- Переменное количество строковых аргументов, объединяемых в команду- Исключение:
DataError -- будет возвращено, если не был получен ответ (или получен некорректный ответ)
CommandError -- Если команда возвращает код состояния ошибки,
SirilError -- Если во время выполнения происходит любая другая ошибка.
Пример
siril.cmd("ght", "-D=0.5", "-b=2.0")
- command_error_message(status_code)
Предоставляет строку, описывающую статус возврата из команды Siril.
- Параметры:
status_code (
CommandStatus
) -- Код статуса, возвращаемый обработчиком команд Siril, или исключением CommandError.- Результат:
Строка, предоставляющая описание кода ошибки, возвращаемого командой Siril, для использования в обработке исключений.
- Тип результата:
str
- confirm_messagebox(title, message, confirm_label)
Создает модальное диалоговое окно подтверждения в Siril и ожидает ответа.
- Параметры:
title (
str
) -- Заголовок, отображаемый в окне сообщения (до 256 символов)message (
str
) -- Сообщение, которое будет отображаться в окне сообщения (до 1021 символа)confirm_label (
str
) -- Надпись, которая будет отображаться на кнопке подтверждения в окне сообщения (OK, Да, Подтвердить и т.д.) (До 24 символов)
- Результат:
True, если была нажата кнопка подтверждения окна сообщения, в противном случае False
- Тип результата:
bool
- Исключение:
DataError -- если ответ не был получен,
SirilError -- если произошла другая ошибка.
- connect()
Устанавливает соединение с Siril на основе именованного канала или пути к сокету.
- Тип результата:
bool
- Результат:
True в случае успеха
- Исключение:
SirilConnectionError -- если произошла ошибка соединения
- 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.
- Параметры:
seq_root (
str
) -- The root name of the sequence to be created.- Результат:
True if the sequence was successfully created, False otherwise.
- Тип результата:
bool
- Исключение:
SirilError -- если произошла ошибка.
- disconnect()
Закрывает установленное соединение через сокет или именованный канал. Обратите внимание, что обычно нет необходимости закрывать это соединение, за исключением случаев, когда по какой-то причине требуется закрыть одно соединение и затем открыть другое. Этот метод автоматически вызывается при завершении скрипта с помощью обработчика
atexit
, поэтому нет необходимости делать это вручную. Вызов этого метода сбросит индикатор прогресса.- Исключение:
SirilConnectionError -- если соединение не было закрыто.
- error_messagebox(my_string, modal=False)
Отправляет сообщение об ошибке в Siril. Максимальная длина сообщения составляет 1022 байта: более длинные сообщения будут обрезаны (однако этого достаточно для окна сообщения об ошибке). Обратите внимание, что окно сообщения об ошибке по умолчанию не является модальным: оно предназначено для более заметного отображения сообщения об ошибке по сравнению с использованием журнала Siril перед закрытием приложения.
- Параметры:
my_string (
str
) -- Сообщение для отображения в окне сообщения об ошибкеmodal (
Optional
[bool
]) -- Устанавливает, должно ли окно сообщения быть модальным и ожидать завершения, или немодальным, позволяя скрипту продолжить выполнение. Обратите внимание, что хотя модальное окно сообщения будет блокировать выполнение скрипта, если запущен основной цикл TKinter, события будут продолжать накапливаться, поэтому, если окно сообщения вызвано нажатием кнопки, пользователь может нажать её снова, пока отображается окно сообщения, и вызвать второе окно сообщения, которое отобразится сразу после закрытия первого.
- Результат:
True, если сообщение об ошибке было успешно отображено, и False в противном случае
- Тип результата:
bool
- Исключение:
SirilError -- если произошла ошибка.
- get_image(with_pixels=True, preview=False)
Запрашивает копию текущего изображения, открытого в Siril.
- Параметры:
with_pixels (
Optional
[bool
]) -- необязательный логический параметр, указывающий, следует ли получать данные пикселей в виде массива NumPy или только метаданные изображения. По умолчанию установлено значение Truepreview (
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)
- Тип результата:
Optional
[FFit
]- Результат:
FFit объект, содержащий метаданные изображения и (опционально) пиксельные данные, или None если произошла ошибка
- Исключение:
NoImageError -- если в Siril не загружено изображение
SirilError -- если произошла ошибка декодирования
- get_image_bgsamples()
Request background samples data from Siril.
- Тип результата:
Optional
[List
[BGSample
]]- Результат:
Список образцов фона BGSamples, где каждая пара координат выражена в виде кортежа [float, float], или None, если не установлены образцы фона.
- Исключение:
NoImageError -- Если в данный момент изображение не загружено,
DataError -- при получении неверных данных,
SirilError -- При других ошибках во время извлечения данных,
- get_image_filename()
Запрашивает имя файла загруженного в Siril изображения.
- Тип результата:
Optional
[str
]- Результат:
Имя файла в виде строки.
- Исключение:
NoImageError -- если нет загруженного изображения,
SirilError -- если произошла ошибка декодирования.
- get_image_fits_header(return_as='str')
Получает полный заголовок FITS текущего изображения, загруженного в Siril.
- Параметры:
return_as -- Optional string specifying the format of the returned header. Can be 'str' for a string or 'dict' for a dictionary.
- Результат:
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.
- Тип результата:
str
- Исключение:
NoImageError -- Если в данный момент изображение не загружено,
SirilError -- При других ошибках во время извлечения данных,
- get_image_history()
Извлекает записи истории из FITS заголовка текущего загруженного в Siril изображения с использованием общедоступной памяти.
- Параметры:
none.
- Результат:
Записи HISTORY из FITS заголовка в виде списка строк, или None, если в заголовке отсутствуют ключевые слова HISTORY.
- Тип результата:
list
- Исключение:
NoImageError -- Если в данный момент изображение не загружено,
SirilError -- При других ошибках во время извлечения данных.
- get_image_iccprofile()
Извлекает ICC профиль текущего изображения Siril, используя общедоступную память.
Args: none.
- Результат:
ICC профиль изображения в виде массива байтов или None, если текущее изображение не имеет ICC профиля.
- Тип результата:
bytes
- Исключение:
NoImageError -- Если в данный момент изображение не загружено,
SirilError -- Если произошла любая другая ошибка.
- get_image_keywords()
Запрашивает данные ключевых слов FITS из Siril в виде объекта FKeywords.
- Тип результата:
Optional
[FKeywords
]- Результат:
Объект FKeywords содержит ключевые слова FITS или None, если произошла ошибка
- Исключение:
SirilError -- если произошла ошибка декодирования.
- get_image_pixeldata(shape=None, preview=False)
Извлекает пиксельные данные из изображения, загруженного в данный момент в Siril.
- Параметры:
shape (
Optional
[list
[int
]]) -- Необязательный список [x, y, w, h], определяющий регион для извлечения. Если указан, получает данные пикселей только для этого региона. Если None, получает данные пикселей для всего изображения.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)
- Результат:
Данные изображения в виде массива numpy
- Тип результата:
numpy.ndarray
- Исключение:
NoImageError -- Если в данный момент изображение не загружено,
ValueError -- Если предоставлена недопустимая форма,
DataError -- если массив невозможно преобразовать к правильным размерностям,
SirilError -- При других ошибках во время извлечения пиксельных данных,
- get_image_shape()
Запрашивает форму изображения у Siril.
- Тип результата:
Optional
[Tuple
[int
,int
,int
]]- Результат:
Кортеж (канал, высота, ширина), представляющий форму изображения, или None, если форма изображения недоступна для возврата.
Вызывает: SirilError: если произошла ошибка.
- get_image_stars()
Запрашивает данные модельной PSF звёзд у Siril.
- Тип результата:
List
[PSFStar
]- Результат:
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.
- Исключение:
NoImageError -- Если в данный момент изображение не загружено,
SirilError -- При других ошибках во время извлечения данных,
- get_image_stats(channel)
Запрашивает статистику изображения у Siril для заданного канала.
- Параметры:
channel (
int
) -- Целое число, указывающее, для какого канала требуется получить статистику (обычно 0, 1 или 2)- Тип результата:
Optional
[ImageStats
]- Результат:
Объект ImageStats, содержащий статистику, или None, если для выбранного канала статистика недоступна
- Исключение:
NoImageError -- если нет загруженного изображения,
SirilError -- если произошла ошибка.
- get_image_unknown_keys()
Извлекает неизвестный ключ в заголовке FITS текущего загруженного изображения в Siril с использованием общедоступной памяти.
- Параметры:
none.
- Результат:
Неизвестные ключи в виде строки или None, если нет ключей.
- Тип результата:
bytes
- Исключение:
NoImageError -- Если в данный момент изображение не загружено,
SirilError -- При других ошибках во время извлечения данных.
- get_selection_star(shape=None, channel=None)
Получает модель звезды PSFStar из текущего выделения в Siril. Возвращается только одна модель PSFStar: если в выделении имеется больше одной звезды, возвращается первая, идентифицированная алгоритмом внутреннего обнаружения звезд Siril.
- Параметры:
shape (
Optional
[list
[int
]]) -- Необязательный список [x, y, w, h], определяющий выделение для получения данных. Размеры w x h не должны превышать 300 x 300 пикселей. Если указан, ищется звезда в указанном выделении. Если None, ищется звезда в уже сделанном в Siril выделении, если оно есть.channel (
Optional
[int
]) -- Необязательное целое число, определяющее канал для получения данных. Если указан: 0 = Красный/Моно, 1 = Зеленый, 2 = Синий. Если канал не указан, то в режиме GUI будет использовано текущее окно просмотра, а если режима GUI нет, метод вернется к каналу 0
- Результат:
Объект PSFStar, представляющий модель звезды, или None, если в выделении не обнаружена ни одна звезда.
- Тип результата:
- Исключение:
ValueError -- Если предоставлена недопустимая форма,
NoImageError -- If no image is loaded,
SirilConnectionError -- If a communication error occurs,
SirilError -- If any other error occurred during execution.
- get_selection_stats(shape=None, channel=None)
Retrieves statistics for the current selection in Siril. :type shape:
Optional
[list
[int
]] :param shape: Optional list of [x, y, w, h] specifying the selection toretrieve 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
]) -- Необязательное целое число, определяющее канал для получения данных. Если указан: 0 = Красный/Моно, 1 = Зеленый, 2 = Синий. Если канал не указан, то в режиме GUI будет использовано текущее окно просмотра, а если режима GUI нет, метод вернется к каналу 0- Результат:
the ImageStats object representing the selection statistics.
- Тип результата:
- Исключение:
SirilError -- If an error occurred during processing,
ValueError -- If an invalid shape is provided.
- get_seq()
Request metadata for the current sequence loaded in Siril.
- Тип результата:
Optional
[Sequence
]- Результат:
Sequence object containing the current sequence metadata, or None if an error occurred
- Исключение:
NoSequenceError -- if no sequence is loaded in Siril,
SirilError -- если произошла ошибка декодирования.
- 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)
- Тип результата:
Optional
[DistoData
]- Результат:
DistoData object containing the channel distortion parameters, or None if an error occurred
- Исключение:
NoSequenceError -- if no sequence is loaded in Siril,
SirilError -- если произошла ошибка декодирования.
- get_seq_frame(frame, with_pixels=True, preview=False)
Request sequence frame as a FFit from Siril.
- Параметры:
frame (
int
) -- Integer specifying which frame in the sequence to retrieve data for (between 0 and Sequence.number)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
- Тип результата:
Optional
[FFit
]- Результат:
FFit object containing the frame data
- Исключение:
NoSequenceError -- if no sequence is loaded in Siril,
DataError -- on receipt of incorrect data,
SirilError -- если произошла ошибка.
- get_seq_frame_filename(frame)
Request the filename of the specified frame of the loaded sequence from Siril.
- Тип результата:
Optional
[str
]- Результат:
Имя файла в виде строки.
- Исключение:
NoSequenceError -- if no sequence is loaded in Siril,
SirilError -- если произошла ошибка декодирования.
- get_seq_frame_header(frame, return_as='str')
Retrieve the full FITS header of an image from the sequence loaded in Siril.
- Параметры:
frame (
int
) -- Integer specifying which frame in the sequence to retrieve data forSequence.number) ((between 0 and)
return_as -- Optional string specifying the format of the returned header. Can be 'str' for a string or 'dict' for a dictionary.
- Результат:
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.
- Тип результата:
str
- Исключение:
NoSequenceError -- If no sequence is currently loaded,
SirilError -- При других ошибках во время извлечения данных,
- get_seq_frame_pixeldata(frame, shape=None, preview=False)
Retrieves the pixel data from a frame in the sequence currently loaded in Siril.
- Параметры:
frame (
int
) -- selects the frame to retrieve pixel data fromshape (
Optional
[List
[int
]]) -- Необязательный список [x, y, w, h], определяющий регион для извлечения. Если указан, получает данные пикселей только для этого региона. Если None, получает данные пикселей для всего изображения.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).
- Результат:
Данные изображения в виде массива numpy
- Тип результата:
numpy.ndarray
- Исключение:
ValueError -- Если предоставлена недопустимая форма,
DataError -- если массив невозможно преобразовать к правильным размерностям,
SirilError -- For other errors during pixel data retrieval.
- get_seq_imgdata(frame)
Request sequence frame metadata from Siril.
- Параметры:
frame (
int
) -- Integer specifying which frame in the sequence to get image metadata for (between 0 and Sequence.number)- Тип результата:
Optional
[ImgData
]- Результат:
ImgData object containing the frame metadata, or None if an error occurred
- Исключение:
NoSequenceError -- if no sequence is loaded in Siril,
SirilError -- если произошла ошибка декодирования.
- get_seq_regdata(frame, channel)
Request sequence frame registration data from Siril.
- Параметры:
frame (
int
) -- Integer specifying which frame in the sequence to get registration data for (between 0 and Sequence.number),channel (
int
) -- Integer specifying which channel to get registration data for (typically 0, 1, or 2)
- Тип результата:
Optional
[RegData
]- Результат:
RegData object containing the registration data, or None if no registration data is available for the specified frame and channel
- Исключение:
NoSequenceError -- if no sequence is loaded in Siril,
SirilError -- если произошла ошибка декодирования.
- get_seq_stats(frame, channel)
Request sequence frame statistics from Siril.
- Параметры:
frame (
int
) -- Integer specifying which frame in the sequence to get statistics data for (between 0 and Sequence.number)channel (
int
) -- Целое число, указывающее, для какого канала требуется получить статистику (обычно 0, 1 или 2)
- Тип результата:
Optional
[ImageStats
]- Результат:
ImageStats object containing the statistics, or None if an error occurred
- Исключение:
NoSequenceError -- if no sequence is loaded in Siril,
SirilError -- если произошла ошибка декодирования.
- get_siril_active_vport()
Request the active viewport from Siril.
- Результат:
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.
- Тип результата:
A SirilVport representing the active vport
- Исключение:
DataError -- if no response or an invalid response is received,
SirilError -- если произошла ошибка.
- get_siril_config(group, key)
Request a configuration value from Siril.
- Параметры:
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)
- Тип результата:
Union
[bool
,int
,float
,str
,List
[str
],None
]- Результат:
The configuration value with appropriate Python type, or None if an error occurred.
- Исключение:
DataError -- if an unknown config type is encountered,
SirilError -- if an error occurred getting the requested config value
- get_siril_configdir()
Request the user config directory used by Siril.
- Тип результата:
str
- Результат:
The user config directory as a string.
- Исключение:
DataError -- if no response is received,
SirilError -- for all other errors.
- get_siril_selection()
Request the image selection from Siril.
- Тип результата:
Optional
[Tuple
[int
,int
,int
,int
]]- Результат:
A tuple (x, y, height, width) representing the current selection, or None if no selection is made.
- Исключение:
SirilError -- если произошла ошибка.
- get_siril_systemdatadir()
Request the system data directory used by Siril.
- Тип результата:
Optional
[str
]- Результат:
The system data directory as a string.
- Исключение:
DataError -- if no response is received,
SirilError -- for all other errors.
- get_siril_userdatadir()
Request the user data directory used by Siril.
- Тип результата:
str
- Результат:
The user data directory as a string.
- Исключение:
DataError -- if no response is received,
SirilError -- for all other errors.
- get_siril_wd()
Request the current working directory from Siril.
- Тип результата:
str
- Результат:
The current working directory as a string.
- Исключение:
DataError -- if no response was obtained,
SirilError -- for all other errors.
- 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.
Example:
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
- Исключение:
ProcessingThreadBusyError -- If the thread is already in use
ImageDialogOpenError -- If an image processing dialog is open
SirilError -- If the thread cannot be claimed or released for other reasons
- 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.
- Параметры:
my_string (
str
) -- The message to display in the info message boxmodal (
Optional
[bool
]) -- Устанавливает, должно ли окно сообщения быть модальным и ожидать завершения, или немодальным, позволяя скрипту продолжить выполнение. Обратите внимание, что хотя модальное окно сообщения будет блокировать выполнение скрипта, если запущен основной цикл TKinter, события будут продолжать накапливаться, поэтому, если окно сообщения вызвано нажатием кнопки, пользователь может нажать её снова, пока отображается окно сообщения, и вызвать второе окно сообщения, которое отобразится сразу после закрытия первого.
- Результат:
True if the info was successfully displayed, False otherwise
- Тип результата:
bool
- Исключение:
SirilError -- если произошла ошибка.
- 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.
- Результат:
True if running in CLI mode, False otherwise.
- Тип результата:
bool
- is_image_loaded()
Check if a single image is loaded in Siril.
- Результат:
True if a single image is loaded, False if a single image is not loaded
- Тип результата:
bool
- Исключение:
DataError -- if no response is received,
SirilError -- for all other errors.
- is_sequence_loaded()
Check if a sequence is loaded in Siril.
- Результат:
True if a sequence is loaded, False if a sequence is not loaded
- Тип результата:
bool
- Исключение:
DataError -- if no response is received,
SirilError -- for all other errors.
- log(my_string, color=LogColor.DEFAULT)
Send a log message to Siril. The maximum message length is 1022 bytes: longer messages will be truncated.
- Параметры:
my_string (
str
) -- The message to logcolor (
LogColor
) -- Defines the text color, defaults to white. See the documentationwhich (for LogColor for an explanation of which colors should be used for)
purposes.
- Исключение:
SirilError -- if the command fails
- Тип результата:
bool
- 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- Результат:
the input updated with the ID assigned by Siril
- Тип результата:
- Исключение:
TypeError -- invalid data provided,
SirilConnectionError -- on a connection failure,
DataError -- on receipt of invalid data,
SirilError -- on any failure
- overlay_clear_polygons()
Clears all user polygons from the Siril overlay
- Результат:
True if the command succeeded, False otherwise
- Тип результата:
bool
- Исключение:
SirilError -- if an error occurred
SharedMemoryError -- if a shared memory error occurred
- overlay_delete_polygon(polygon_id)
Deletes a single user polygon from the Siril overlay, specified by ID
- Параметры:
id -- int specifying the polygon ID to be deleted
- Исключение:
SirilError -- on failure
- 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.
- Параметры:
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
- Параметры:
id -- int specifying the polygon ID to be retrieved. The special ID -1 will
retrieve the most recently added polygon.
- Результат:
the specified Polygon if it exists, None otherwise
- Тип результата:
- Исключение:
SirilError -- on failure
- overlay_get_polygons_list()
Gets a List of all user polygons from the Siril overlay
- Результат:
the list of Polygon if some exist, None otherwise
- Тип результата:
List[Polygon]
- Исключение:
SirilError -- if an error occurred
SharedMemoryError -- if a shared memory error occurred
- 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).
- Параметры:
x (
float
) -- float: provides the x coordinate to be convertedy (
float
) -- float: provides the y coordinate to be converted
- Результат:
(RA, Dec) as a Tuple of two floats.
- Тип результата:
Tuple[float, float]
- Исключение:
NoImageError -- If no image or sequence is loaded,
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).
- Параметры:
ra (
float
) -- float: provides the RA coordinate to be converteddec (
float
) -- float: provides the dec coordinate to be converted
- Результат:
[x, y] as a Tuple of two floats.
- Тип результата:
Tuple[float, float]
- Исключение:
NoImageError -- If no image or sequence is loaded,
ValueError -- If the image or loaded sequence frame is not plate solved,
SirilError -- For errors during radec2pix execution.
- reset_progress()
Resets the Siril progress bar.
- Параметры:
none
- Исключение:
SirilError -- For any errors.
- Тип результата:
bool
- 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
- Параметры:
points (
Union
[List
[Tuple
[float
,float
]],List
[BGSample
]]) -- List of sample points, either as (x,y) tuples or BGSample objectsshow_samples (
bool
) -- Whether to show the sample points in Sirilrecalculate -- 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
- Исключение:
NoImageError -- if no image is loaded in Siril,
ValueError -- if samples do not have valid positions,
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.
Example:
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)
- Параметры:
header (
str
) -- string containing the FITS header data- Результат:
True if successful, False otherwise
- Тип результата:
bool
- Исключение:
TypeError -- invalid parameter provided,
NoImageError -- if no image is loaded in Siril,
SirilError -- если произошла ошибка.
- set_image_pixeldata(image_data)
Send image data to Siril using shared memory.
- Параметры:
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.- Исключение:
NoImageError -- if no image is loaded in Siril,
ValueError -- if the input array is invalid,
SirilError -- if there was an error in handling the command.
- Тип результата:
bool
- set_seq_frame_incl(index, incl)
Set whether a given frame is included in the currently loaded sequence in Siril. This method is intended for use in creating custom sequence filters.
- Параметры:
index (
int
) -- integer specifying which frame to set the pixeldata for.incl (
bool
) -- bool specifying whether the frame is included or not.
- Исключение:
NoSequenceError -- if no sequence is loaded in Siril,
SirilError -- on failure.
- set_seq_frame_pixeldata(index, image_data)
Send image data to Siril using shared memory.
- Параметры:
index (
int
) -- integer specifying which frame to set the pixeldata for.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.
- Исключение:
NoSequenceError -- if no sequence is loaded in Siril,
ValueError -- if the input array is invalid,
SirilError -- if there was an error in handling the command.
- Тип результата:
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.
- Параметры:
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()
- Исключение:
SirilError -- если произошла ошибка.
ValueError -- if parameters are not properly provided.
- Результат:
True if the selection was set successfully
- Тип результата:
bool
- undo_save_state(my_string)
Saves an undo state. The maximum message length is 70 bytes: longer messages will be truncated.
- Параметры:
my_string (
str
) -- The message to log in FITS HISTORY- Результат:
True if the message was successfully logged, False otherwise
- Тип результата:
bool
- Исключение:
SirilError -- если произошла ошибка.
- update_progress(message, progress)
Send a progress update to Siril with a message and completion percentage.
- Параметры:
message (
str
) -- Status message to display,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.
- Исключение:
ValueError -- If the progress argument is out of range,
SirilError -- For any other errors.
- Тип результата:
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.
- Параметры:
my_string (
str
) -- The message to display in the warning message boxmodal (
Optional
[bool
]) -- Устанавливает, должно ли окно сообщения быть модальным и ожидать завершения, или немодальным, позволяя скрипту продолжить выполнение. Обратите внимание, что хотя модальное окно сообщения будет блокировать выполнение скрипта, если запущен основной цикл TKinter, события будут продолжать накапливаться, поэтому, если окно сообщения вызвано нажатием кнопки, пользователь может нажать её снова, пока отображается окно сообщения, и вызвать второе окно сообщения, которое отобразится сразу после закрытия первого.
- Результат:
True if the warning was successfully displayed, False otherwise
- Тип результата:
bool
- Исключение:
SirilError -- если произошла ошибка.
- 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()
- Параметры:
plot_metadata -- PlotMetadata object containing plot configuration
display -- bool indicating whether to display the plot on screen (defaults to True)
save -- bool indicating whether to save to the file specified in PlotData.savename (defaults to False)
- Исключение:
DataError -- if invalid xy_plot data is received via shared memory,
SirilError -- If an error occurs.
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)
Базовые классы:
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
- Параметры:
data (bytes) -- The full binary buffer containing BGSample data
- Результат:
A BGSample object
- Тип результата:
- Исключение:
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) Median values for R, G and B channels. For mono images only median[0] is used.
-
min:
float
= 0.0
-
position:
Optional
[Tuple
[float
,float
]] = None Position in (x, y) image coordinates
-
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))
Базовые классы:
object
Python equivalent of Siril disto_params structure
-
filename:
str
= '' filename if DISTO_FILE or DISTO_MASTER (and optional for DISTO_FILE_COMET)
-
velocity:
Tuple
[float
,float
] = (0, 0) shift velocity if DISTO_FILE_COMET
-
filename:
- 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)
Базовые классы:
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.
- Исключение:
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
- Параметры:
target_type -- Optional np.dtype to convert to. If None, uses self.type
- Исключение:
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])
- Параметры:
array (np.ndarray) -- 2D array of image pixels (np.uint16 or np.float32).
nullcheck (bool) -- If True, check for null values.
nullvalue (
Optional
[float
]) -- The value of null pixels (only used if nullcheck is True).
- Результат:
Estimated noise value.
- Тип результата:
float
- Исключение:
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()
- Тип результата:
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:
Optional
[BitpixType
] = None FITS header specification of the image data type.
- property channels: int
Каналы изображения
-
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:
Optional
[str
] = None The FITS header as a string.
- property height: int
Высота изображения
-
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.
-
maxi:
float
= 0.0 The maximum value across all image channels.
-
mini:
float
= 0.0 The minimum value across all image channels.
- 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 The number of axes (2 for a mono image, 3 for a RGB image). Corresponds to the FITS kwyword NAXIS.
-
neg_ratio:
float32
= 0.0 The ratio of negative pixels to the total pixels.
-
orig_bitpix:
Optional
[BitpixType
] = None FITS header specification of the original image data type.
-
stats:
List
[Optional
[ImageStats
]] 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:
Optional
[str
] = None All unknown FITS header keys as a string. This gives access to header cards that Siril does not use internally.
- property width: int
Ширина изображения
- 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)
Базовые классы:
object
Python equivalent of Siril fkeywords structure. Contains the FITS header keyword values converted to suitable data types.
- classmethod deserialize(data)
Deserialize binary response into an FKeywords object.
Args: response: Binary data to unpack
Returns: (FKeywords) object
- Тип результата:
- Raises: ValueError: If received data size is incorrect
struct.error: If unpacking fails
-
airmass:
float
= 1.0 Airmass at frame center (Gueymard 1993)
-
aperture:
float
= 0.0 Aperture value as a float
-
bayer_pattern:
str
= '' Цветной шаблон Байера
-
bayer_xoffset:
int
= 0 Смещение шаблона Байера по X
-
bayer_yoffset:
int
= 0 Смещение шаблона Байера по Y
-
binning_x:
int
= 1 XBINNING FITS header card as an int
-
binning_y:
int
= 1 YBINNING FITS header card as an int
-
bscale:
float
= 1.0 Смещение диапазона данных к диапазону коротких целых без знака
-
bzero:
float
= 0.0 Коэффициент масштабирования по умолчанию
-
ccd_temp:
float
= 0.0 CCD temperature as a float
-
centalt:
float
= 0.0 [град.] Высота телескопа
-
centaz:
float
= 0.0 [град.] Азимут телескопа
-
cvf:
float
= 0.0 Коэффициент преобразования (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:
Optional
[datetime
] = None Дата (по UTC), когда этот файл FITS был создан
-
date_obs:
Optional
[datetime
] = None ss observation start, UT
- Type:
YYYY-MM-DDThh
- Type:
мм
-
expend:
float
= 0.0 Окончание экспозиции как Юлианская дата
-
exposure:
float
= 0.0 Exposure time as a float (s)
-
expstart:
float
= 0.0 Начало экспозиции как Юлианская дата
-
fhi:
float32
= 0.0 MIPS-Hi key in FITS file, "Upper visualization cutoff (float)"
-
filename:
str
= '' Original Filename
-
filter:
str
= '' Название активного фильтра
-
flength:
float
= 0.0 [мм] Фокусное расстояние
-
flo:
float32
= 0.0 MIPS-LO key in FITS file, "Lower visualization cutoff (float)"
-
focal_length:
float
= 0.0 [мм] Фокусное расстояние
-
focname:
str
= '' Название фокусировчного оборудования
-
foctemp:
float
= 0.0 Температура фокусёра
-
focuspos:
int
= 0 Положение фокусёра
-
focussz:
int
= 0 [мкм] Шаг фокусёра
-
gain:
int
= 0 Gain factor read in camera
-
hi:
int
= 0 MIPS-HI key in FITS file, "Upper visualization cutoff"
-
image_type:
str
= '' Тип изображения
-
instrume:
str
= '' Название инструмента
-
iso_speed:
float
= 0.0 ISO speed value as a float
-
livetime:
float
= 0.0 Sum of exposure times (s)
-
lo:
int
= 0 MIPS-LO key in FITS file, "Lower visualization cutoff"
-
object:
str
= '' Название объекта интереса
-
observer:
str
= '' Имя наблюдателя
-
offset:
int
= 0 Offset value read in camera
-
pixel_size_x:
float
= 0.0 XPIXSZ FITS header card as a float
-
pixel_size_y:
float
= 0.0 YPIXSZ FITS header card as a float
-
program:
str
= '' Программное обеспечение, использованное для создания этого HDU
-
row_order:
str
= '' Порядок строк в массиве изображения
-
set_temp:
float
= 0.0 CCD set temperature as a float
-
siteelev:
float
= 0.0 [м] Высота места наблюдения
-
sitelat:
float
= 0.0
-
sitelat_str:
str
= ''
-
sitelong:
float
= 0.0 Долгота места наблюдения (в градусах)
-
sitelong_str:
str
= ''
-
stackcnt:
int
= 0 Number of stacked frames
-
telescop:
str
= '' Телескоп, использованный для получения этого изображения
- class sirilpy.models.FPoint(x, y)
Базовые классы:
object
Represents a 2D point with float x and y coordinate values in the Siril image.
-
x:
float
x co-ordinate
-
y:
float
y co-ordinate
-
x:
- 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)
Базовые классы:
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 Homography matrix H00
-
h01:
float
= 0.0 Homography matrix H01
-
h02:
float
= 0.0 Homography matrix H02
-
h10:
float
= 0.0 Homography matrix H10
-
h11:
float
= 0.0 Homography matrix H11
-
h12:
float
= 0.0 Homography matrix H12
-
h20:
float
= 0.0 Homography matrix H20
-
h21:
float
= 0.0 Homography matrix H21
-
h22:
float
= 0.0 Homography matrix H22
-
pair_matched:
int
= 0 number of pairs matched
-
Inliers:
- 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)
Базовые классы:
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.
- Параметры:
data (
bytes
) -- (bytes) Binary data to unpack- Тип результата:
Returns: ImageStats object
- Raises: SirilError: If received data size is incorrect
struct.error: If unpacking fails
-
avgDev:
float
= 0.0 average deviation of pixels
-
bgnoise:
float
= 0.0 RMS background noise
-
location:
float
= 0.0 location of pixel values
-
mad:
float
= 0.0 mean average deviation of pixels
-
max:
float
= 0.0 maximum pixel value
-
mean:
float
= 0.0 mean value of pixels
-
median:
float
= 0.0 median value of pixels
-
min:
float
= 0.0 minimum pixel value
-
ngoodpix:
int
= 0 number of non-zero pixels
-
normValue:
float
= 0.0 norm value of the pixels
-
scale:
float
= 0.0 scale value of the pixels
-
sigma:
float
= 0.0 standard deviation of pixels
-
sqrtbwmv:
float
= 0.0 square root of the biweight midvariance of pixel values
-
total:
int
= 0 total number of pixels
- class sirilpy.models.ImgData(filenum=0, incl=False, date_obs=None, airmass=0.0, rx=0, ry=0)
Базовые классы:
object
Python equivalent of Siril imgdata structure
- classmethod deserialize(response)
Deserialize binary response into an ImgData object.
- Параметры:
response (bytes) -- Binary data to unpack.
- Результат:
An ImgData object with deserialized data.
- Тип результата:
- Исключение:
ValueError -- If received data size is incorrect.
struct.error -- If unpacking fails.
-
airmass:
float
= 0.0 airmass of the image
-
date_obs:
Optional
[datetime
] = None date of the observation
-
filenum:
int
= 0 real file index in the sequence
-
incl:
bool
= False selected in the sequence
-
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, 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)
Базовые классы:
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.
- Параметры:
data (
bytes
) -- (bytes) The full binary buffer containing PSFStar data.- Тип результата:
- Результат:
PSFStar object
- Исключение:
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 error in A
-
B:
float
= 0.0 average sky background value
-
BV:
float
= 0.0 only used to pass data in photometric color calibration
-
B_err:
float
= 0.0 error in B
-
Bmag:
float
= 0.0 B magnitude
-
R:
int
= 0 Optimized box size to enclose sufficient pixels in the background
-
SNR:
float
= 0.0 SNR of the star
-
ang_err:
float
= 0.0 error in angle
-
angle:
float
= 0.0 angle of the x and yaxes with respect to the image x and y axes
-
beta:
float
= 0.0 Moffat equation beta parameter
-
beta_err:
float
= 0.0 error in beta
-
dec:
float
= 0.0 Declination
-
fwhmx:
float
= 0.0 FWHM in x axis in pixels
-
fwhmx_arcsec:
float
= 0.0 FWHM in x axis in arc seconds
-
fwhmy:
float
= 0.0 FWHM in y axis in pixels
-
fwhmy_arcsec:
float
= 0.0 FWHM in y axis in 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 magnitude, approximate or accurate
-
profile:
StarProfile
= 0
-
ra:
float
= 0.0 Right Ascension
-
rmse:
float
= 0.0 RMSE of the minimization
-
s_Bmag:
float
= 999.99 error on the B magnitude
-
s_mag:
float
= 999.99 error on the (V) magnitude
-
sat:
float
= 0.0 Level above which pixels have satured
-
star_name:
Optional
[str
] = None
-
sx:
float
= 0.0 Size of the fitted function on the x axis in PSF coordinates
-
sx_err:
float
= 0.0 error in sx
-
sy:
float
= 0.0 Size of the fitted function on the y axis in PSF coordinates
-
sy_err:
float
= 0.0 error in sy
-
units:
Optional
[str
] = None Units
-
x0:
float
= 0.0 x coordinate of the peak
-
x_err:
float
= 0.0 error in x
-
xpos:
float
= 0.0 x position of the star in the image
-
y0:
float
= 0.0 y coordinate of the peak
-
y_err:
float
= 0.0 error in 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)
Базовые классы:
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.
- polygon_id
A unique identifier for the polygon.
- Type:
int
- color
Packed RGBA color (32-bit integer).
- Type:
int
- fill
If True, the polygon should be filled when drawn.
- Type:
bool
- legend
Optional legend for the polygon.
- Type:
str
- classmethod deserialize_polygon(data)
Creates a Polygon object by deserializing a byte array.
- Результат:
- 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.)
- Тип результата:
Tuple
- Исключение:
ValueError -- If there is insufficient data to deserialize.
- classmethod deserialize_polygon_list(data)
Creates a List of Polygon objects by deserializing a byte array.
- Результат:
A List of Polygon objects.
- Тип результата:
List
- Исключение:
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().
- Параметры:
rect (Tuple[int, int, int, int]) -- Rectangle as (x, y, width, height)
**kwargs -- Additional keyword arguments to pass to Polygon constructor (polygon_id, color, fill, legend)
- Результат:
A new Polygon instance representing the rectangle
- Тип результата:
- 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.
- Параметры:
x (float) -- X coordinate of the point to test.
y (float) -- Y coordinate of the point to test.
- Результат:
True if the point is inside the polygon, False otherwise.
- Тип результата:
bool
- get_bounds()
Get the bounding box of the polygon.
- Результат:
(min_x, min_y, max_x, max_y)
- Тип результата:
Tuple[float, float, float, float]
- Исключение:
ValueError -- If the polygon has no points.
- get_max_x()
Get the maximum x coordinate of the polygon.
- Тип результата:
float
- get_max_y()
Get the maximum y coordinate of the polygon.
- Тип результата:
float
- get_min_x()
Get the minimum x coordinate of the polygon.
- Тип результата:
float
- get_min_y()
Get the minimum y coordinate of the polygon.
- Тип результата:
float
- serialize()
Serializes a single Polygon object into a byte array.
- Результат:
A byte array representing the serialized polygon data.
- Тип результата:
bytes
- Исключение:
ValueError -- If the number of points exceeds the allowed limit.
-
color:
int
= 4294967295 no-index:
- Type:
32-bit RGBA color (packed, uint_8 per component. Default value is 0xFFFFFFFF)
-
fill:
bool
= False no-index:
- Type:
whether or not the polygon should be filled when drawn
-
legend:
str
= None no-index:
- Type:
an optional legend
-
polygon_id:
int
= 0 no-index:
- Type:
unique identifier
- 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>)
Базовые классы:
object
Python equivalent of Siril regdata structure
- classmethod deserialize(data)
Deserialize a binary response into a RegData object.
- Параметры:
data (bytes) -- Binary data to unpack
- Тип результата:
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 background level
-
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 measure of image quality
-
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)
Базовые классы:
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 file number currently loaded
-
end:
int
= 0 imgparam[number-1]->filenum
-
exposure:
float
= 0.0 exposure of frames
-
fixed:
int
= 0 fixed length of image index in filename
-
fz:
bool
= False whether the file is compressed
-
is_variable:
bool
= False sequence has images of different sizes
-
nb_layers:
int
= -1 number of layers embedded in each image file
-
number:
int
= 0 number of images in the sequence
-
reference_image:
int
= 0 reference image for registration
-
rx:
int
= 0 first image width
-
ry:
int
= 0 first image height
-
selnum:
int
= 0 number of selected images
-
seqname:
str
= '' name of the sequence
-
stats:
List
[List
[ImageStats
]] = None statistics of the images for each layer [nb_layers][number]
-
type:
SequenceType
= None the type of sequence
-
beg:
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)
Базовые классы:
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)
Базовые классы:
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.DistoType(value)
Базовые классы:
IntEnum
Python equivalent of the Siril disto_source enum
- DISTO_FILE = 2
Distortion from given file
- 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
Distortion from current image
- DISTO_MASTER = 3
Distortion from master files
- DISTO_UNDEF = 0
No distortion
- class sirilpy.enums.LogColor(value)
Базовые классы:
IntEnum
Defines colors available for use with
SirilInterface.log()
For consistencyLogColor.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, andLogColor.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)
Базовые классы:
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.SequenceType(value)
Базовые классы:
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
Базовые классы:
object
Defines the Siril viewports
- BLUE = 2
- GREEN = 1
- MONO = 0
- RED = 0
- RGB = 3
- class sirilpy.enums.StarProfile(value)
Базовые классы:
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)
Базовые классы:
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.
- Members:
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.
- Параметры:
plot_data (
PlotData
) -- PlotData object containing plot configuration- Тип результата:
Tuple
[bytes
,int
]- Результат:
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.
- Результат:
the created SeriesData object for further manipulation if needed.
- Тип результата:
- add_series_obj(series)
Add a pre-created SeriesData object to the plot metadata.
Returns: None
- Тип результата:
None
- class sirilpy.plot.SeriesData(x_coords, y_coords, label=None, plot_type=PlotType.LINES, n_error=None, p_error=None)
Базовые классы:
object
Represents a single data series for plotting.
- Members:
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
Базовые классы:
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
Базовые классы:
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.
Пример
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.
- Параметры:
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'
- Результат:
True if requires = None or if the available sirilpy module version satisfies the version specifier, otherwise False
- Исключение:
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.
- Параметры:
siril (SirilInterface) -- SirilInterface to use to update the progress bar
url (str) -- URL of the file to download
file_path (str) -- Local path to save the downloaded file
max_retries (int) -- Number of download retry attempts
retry_delay (int) -- Delay between retry attempts in seconds
resume (bool) -- Whether or not to resume a partially downloaded file or start again
- Результат:
True if download successful, False otherwise
- Тип результата:
bool
- Исключение:
SirilError -- On unhandled errors
- sirilpy.utility.ensure_installed(*packages, version_constraints=None)
Ensures that the specified package(s) are installed and meet optional version constraints.
- Параметры:
*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.
- Результат:
True if all packages are successfully installed or already meet constraints.
- Тип результата:
bool
- Исключение:
SirilError -- If package installation fails,
ValueError -- If a different number of constraints is provided to the number of packages to be installed.
TimeoutError -- If pip fails with an apparent timeout.
- sirilpy.utility.human_readable_size(bytes_size)
Convert bytes to human-readable format.
- Параметры:
bytes_size (int) -- Size in bytes
- Результат:
Formatted size with appropriate unit (B, KB, MB, GB, TB)
- Тип результата:
str
- Исключение:
TypeError -- on incorrect input type
- sirilpy.utility.parse_fits_header(header_text)
Parse FITS header from text content into a dictionary
Parameters: header_text (str): Content of the FITS header text file
Returns: dict: Dictionary containing all header keywords and values
- Тип результата:
dict
- sirilpy.utility.truncate_utf8(data, max_bytes)
Truncates utf8 input. Accepts either bytes or str as input and returns data in the same format as the input.
- Параметры:
data (bytes or str) -- The data to be truncated
- Результат:
The truncated data
- Тип результата:
bytes or str
- Исключение:
TypeError -- if the input was not bytes or str
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
Базовые классы:
object
A helper class for detecting, installing, and testing JAX with appropriate hardware acceleration.
This class automatically detects the system configuration and installs the correct JAX variant (CPU, CUDA, ROCm, etc.) based on available hardware.
- ensure_jax()
Wrapper for install_jax() that only installs it if needed, with negligible overhead if it is already installed.
- Тип результата:
bool
- install_jax(force_variant=None, version_constraint=None)
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
- Параметры:
force_variant (
Optional
[str
]) -- Override auto-detection with specific variant (e.g., 'jax[cpu]')version_constraint (
Optional
[str
]) -- Version constraint string (e.g., '>=0.4.0')
- Результат:
True if installation succeeded, False otherwise
- Тип результата:
bool
- is_jax_installed()
Check if PyTorch is installed without importing it.
- Тип результата:
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.
- Результат:
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
- Тип результата:
Tuple[bool,str]
- Исключение:
RuntimeError -- If JAX computation fails or accuracy check fails
ImportError -- If JAX is not installed
- 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).
- Параметры:
dry_run (
bool
) -- If True, only detect packages without uninstalling them- Тип результата:
Dict
[str
,Any
]- Результат:
Dict containing information about detected and uninstalled packages
- class sirilpy.gpuhelper.ONNXHelper
Базовые классы:
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.
- Тип результата:
bool
- get_execution_providers_ordered(ai_gpu_acceleration=True)
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. :type ai_gpu_acceleration: :param ai_gpu_acceleration: Whether to include GPU acceleration providers.
Defaults to True.
- Результат:
Ordered list of available execution providers.
- Тип результата:
list
- install_onnxruntime()
Detect system configuration and install the appropriate ONNX Runtime package.
- Результат:
True if installation was successful or already installed, False otherwise.
- Тип результата:
bool
- Исключение:
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.
- Результат:
- (is_installed, package_name) where package_name could be
'onnxruntime', 'onnxruntime-gpu', 'onnxruntime-silicon', etc.
- Тип результата:
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.
- Параметры:
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
- Результат:
- (result, session) where result is the inference output (or first output if return_first_output=True) and
session is the (potentially updated) inference session
- Тип результата:
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)
Test an imported onnxruntime. 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.
- Результат:
a list of confirmed working ONNXRuntime ExecutionProviders in priority order
- Тип результата:
list
- uninstall_onnxruntime()
Detects and uninstalls all variants of onnxruntime packages. Checks for any package starting with 'onnxruntime'.
- Результат:
A list of uninstalled packages
- Тип результата:
list
- class sirilpy.gpuhelper.TorchHelper
Базовые классы:
object
Helper class for PyTorch detection, installation and testing.
- ensure_torch()
Wrapper for install_torch() that only installs it if needed, with negligible overhead if it is already installed.
- Тип результата:
bool
- install_torch(cuda_version='auto', force_reinstall=False)
Install PyTorch with GPU compute platform support where available and stable. Use this in place of ensure_installed() to make sure that the correct Torch package is installed for the user's hardware and OS.
- Параметры:
cuda_version (
str
) -- compute platform to install (e.g., 'cu118', 'cu126', 'cu128', 'rocm', 'cpu', 'auto')force_reinstall (
bool
) -- Whether to reinstall even if already installed
- Результат:
True if installation successful, False otherwise
- Тип результата:
bool
- is_torch_installed()
Check if PyTorch is installed without importing it.
- Тип результата:
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 TK GUI
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.
Предупреждение
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.
- class sirilpy.tksiril.ScrollableFrame(container, *args, **kwargs)
Базовые классы:
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).
- Usage:
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.
- Параметры:
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.
Пример
# 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.
- Параметры:
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.
- Исключение:
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.
- Параметры:
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
- Исключение:
TypeError -- If input arguments are of incorrect type
ValueError -- If the theme configuration is not 0 or 1
AttributeError -- If required methods are not available
RuntimeError -- If there are errors installing or setting the theme
- sirilpy.tksiril.standard_style()
Provide a standardised ttk style to allow consistent visual appearance between different Siril python scripts.
- Параметры:
none
- Исключение:
SirilError -- If the style creation or configuration fails
Sirilpy Tkfilebrowser
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 fortkfilebrowser.askopendirname()
to maintain compatibility withtk.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)
Базовые классы:
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')
Базовые классы:
SirilError
Raised when there are problems with data handling. This includes cases like:
Invalid image data
Data conversion errors
Memory allocation failures
Buffer overflows
- exception sirilpy.exceptions.ImageDialogOpenError(message='Siril image dialog is open')
Базовые классы:
SirilError
Exception raised when an image processing dialog is open.
- exception sirilpy.exceptions.MouseModeError(message='Siril mouse mode error')
Базовые классы:
SirilError
Exception raised when Siril is in the wrong mouse mode.
- exception sirilpy.exceptions.NoImageError(message='No Siril image loaded')
Базовые классы:
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')
Базовые классы:
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')
Базовые классы:
SirilError
Exception raised when the processing thread is already in use.
Базовые классы:
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')
Базовые классы:
SirilError
Raised when there are problems connecting to or communicating with Siril. This includes cases like:
Siril not running
Socket connection failures
Communication protocol errors
Unexpected disconnections
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')
Базовые классы:
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.