jupyter

package
v0.0.0-...-9378be4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2023 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package jupyterclient provides a simple Jupyter Protocol client for communication with Jupyter kernels.

Note: Currently, the package does not support stdin prompting as described in https://jupyter-protocol.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-channel

Index

Constants

This section is empty.

Variables

View Source
var (
	// Version of jupyter protocol.
	Version = "5.3"

	// ErrInvalidSignature is returned when received message with an invalid signature.
	ErrInvalidSignature = errors.New("Invalid jupyter protocol signature")
)
View Source
var (
	RequestExecute = "execute_request"
	RequestInspect = "inspect_request"
	RequestHistory = "history_request"
)

Functions

This section is empty.

Types

type ClearOutputMessage

type ClearOutputMessage struct {
	// Wait indicates whether to clear the output immediately before new output is displayed.
	// If true, the output is cleared only when new output is available.
	Wait bool `json:"wait"`
}

ClearOutputMessage represents a Jupyter message for clearing output. This message type is used to clear the output, optionally waiting for new output to be available. Useful for creating animations with minimal flickering.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client - Jupyter kernel client.

func NewClient

func NewClient(ctx context.Context, info *ConnectionInfo) (_ *Client, err error)

func (*Client) Close

func (client *Client) Close() error

func (*Client) Execute

func (client *Client) Execute(req *ExecutionRequest) (rep ExecutionResult, ch <-chan interface{}, err error)

func (*Client) History

func (client *Client) History(req *HistoryRequest) (rep HistoryReply, err error)

func (*Client) Inspect

func (client *Client) Inspect(req *IntrospectionRequest) (rep InspectReply, err error)

type CompleteReply

type CompleteReply struct {
	// Matches is the list of all matches to the completion request.
	// Example: ['a.isalnum', 'a.isalpha'] for the provided code context.
	Matches []string `json:"matches"`

	// CursorStart is the start position of the text that should be replaced by the completion matches.
	// Typically, CursorEnd is the same as CursorPos in the request.
	CursorStart int `json:"cursor_start"`

	// CursorEnd is the end position of the text that should be replaced by the completion matches.
	CursorEnd int `json:"cursor_end"`

	// Metadata is information that frontend plugins might use for extra display information about completions.
	Metadata map[string]interface{} `json:"metadata"`

	// Status should be 'ok' unless an exception was raised during the request.
	// If there is an error, Status will be 'error' along with the usual error message content.
	Status string `json:"status"`
}

CompleteReply represents the content of a complete_reply message in the Jupyter protocol.

type CompleteRequest

type CompleteRequest struct {
	// Code is the code context in which completion is requested.
	// This may be up to an entire multiline cell.
	// Example: 'foo = a.isal'
	Code string `json:"code"`

	// CursorPos is the cursor position within 'Code' (in Unicode characters) where completion is requested.
	CursorPos int `json:"cursor_pos"`
}

CompleteRequest represents the content of a complete_request message in the Jupyter protocol.

type ConnectionInfo

type ConnectionInfo struct {
	SignatureScheme string `json:"signature_scheme"`
	Transport       string `json:"transport"`
	IP              string `json:"ip"`
	Key             string `json:"key"`
	StdinPort       int    `json:"stdin_port"`
	ControlPort     int    `json:"control_port"`
	IoPubPort       int    `json:"iopub_port"`
	HeartBeatPort   int    `json:"hb_port"`
	ShellPort       int    `json:"shell_port"`
}

ConnectionInfo - Jupyter kernel connection info.

func ReadConfigFile

func ReadConfigFile(path string) (info ConnectionInfo, err error)

func (*ConnectionInfo) IoPubAddr

func (info *ConnectionInfo) IoPubAddr() string

func (*ConnectionInfo) ShellAddr

func (info *ConnectionInfo) ShellAddr() string

type DisplayData

type DisplayData struct {
	// Data contains key/value pairs where keys are MIME types,
	// and values are the raw data of the representation in that format.
	Data map[string]interface{} `json:"data"`

	// Metadata is any metadata that describes the data.
	Metadata map[string]interface{} `json:"metadata"`

	// Transient contains optional transient data introduced in version 5.1.
	// This information is not persisted to a notebook or other documents
	// and is intended to live only during a live kernel session.
	Transient map[string]interface{} `json:"transient"`
}

DisplayData represents a message type for displaying data.

type DisplayDataMessage

type DisplayDataMessage struct {
	// Data contains key/value pairs, where keys are MIME types, and values are raw data of the representation in that format.
	Data map[string]interface{} `json:"data"`

	// Metadata contains any metadata that describes the data.
	Metadata map[string]interface{} `json:"metadata"`

	// Transient contains optional transient data introduced in 5.1.
	// This information is not persisted to a notebook or other documents and is intended to live only during a live kernel session.
	Transient map[string]interface{} `json:"transient"`
}

DisplayDataMessage represents the content of a display_data message in the Jupyter protocol.

type ErrorMessage

type ErrorMessage struct {
	// EName is the exception name, as a string.
	EName string `json:"ename"`

	// EValue is the exception value, as a string.
	EValue string `json:"evalue"`

	// Traceback is a list of traceback frames as strings.
	Traceback []string `json:"traceback"`
}

ErrorMessage represents the content of an error message in the Jupyter protocol.

type ExecuteInputMessage

type ExecuteInputMessage struct {
	// Code is the source code to be executed, one or more lines.
	Code string `json:"code"`

	// ExecutionCount is the counter for this execution.
	ExecutionCount int `json:"execution_count"`
}

ExecuteInputMessage represents the content of an execute_input message in the Jupyter protocol.

type ExecuteResultMessage

type ExecuteResultMessage struct {
	// ExecutionCount is the counter for this execution.
	ExecutionCount int `json:"execution_count"`

	// Data and Metadata are identical to a display_data message.
	// The object being displayed is that passed to the display hook, i.e., the result of the execution.
	Data     map[string]interface{} `json:"data"`
	Metadata map[string]interface{} `json:"metadata"`
}

ExecuteResultMessage represents the content of an execute_result message in the Jupyter protocol.

type ExecutionRequest

type ExecutionRequest struct {
	// Code to be executed by the kernel, one or more lines.
	Code string `json:"code"`

	// Silent, if true, signals the kernel to execute quietly without broadcasting output.
	// Defaults to false.
	Silent bool `json:"silent"`

	// StoreHistory, if true, signals the kernel to populate history.
	// Defaults to true if Silent is false.
	StoreHistory bool `json:"store_history"`

	// UserExpressions is a map of names to expressions to be evaluated in the user's dict.
	// The rich display-data representation of each will be evaluated after execution.
	// See the display_data content for the structure of the representation data.
	UserExpressions map[string]string `json:"user_expressions"`

	// AllowStdin, if true, indicates that the code running in the kernel can prompt the user for input.
	AllowStdin bool `json:"allow_stdin"`

	// StopOnError, if true, does not abort the execution queue if an exception is encountered.
	// Allows queued execution of multiple execute_requests, even if they generate exceptions.
	StopOnError bool `json:"stop_on_error"`
}

ExecutionRequest represents a request to execute source code by the kernel. https://jupyter-protocol.readthedocs.io/en/latest/messaging.html#execute

type ExecutionResult

type ExecutionResult struct {
	// Status indicates the result status and can be one of: 'ok', 'error', or 'abort'.
	Status Status `json:"status"`

	// ExecutionCount is the global kernel counter that increases with each request storing history.
	// Typically used by clients to display prompt numbers to the user.
	// If the request did not store history, this will be the current value of the counter in the kernel.
	ExecutionCount int `json:"execution_count"`

	// Payload is a list of payload dictionaries (optional and considered deprecated).
	// Each payload dict must have a 'source' key, classifying the payload (e.g., 'page').
	Payload []map[string]interface{} `json:"payload,omitempty"`

	// UserExpressions contains results for user_expressions if the status is 'ok'.
	UserExpressions map[string]DisplayData `json:"user_expressions,omitempty"`
}

ExecutionResult represents the result of a code execution request. https://jupyter-protocol.readthedocs.io/en/latest/messaging.html#execution-results

type Header struct {
	// MsgID is a unique identifier for the message, typically a UUID.
	MsgID string `json:"msg_id"`

	// Username is the username for the process that generated the message.
	Username string `json:"username"`

	// Session is a unique identifier for the session, typically a UUID.
	Session string `json:"session"`

	// Date is an ISO 8601 timestamp for when the message is created.
	Date string `json:"date"`

	// MsgType is the type of the message.
	MsgType string `json:"msg_type"`

	// Version is the message protocol version.
	Version string `json:"version"`
}

https://jupyter-protocol.readthedocs.io/en/latest/messaging.html#general-message-format

type HistoryItem

type HistoryItem struct {
	Session    int
	LineNumber int
	Input      string
	Output     interface{}
}

HistoryItem represents a single history item with session, line number, and optional output.

func (*HistoryItem) MarshalJSON

func (item *HistoryItem) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for HistoryItem.

func (*HistoryItem) UnmarshalJSON

func (item *HistoryItem) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for HistoryItem.

type HistoryReply

type HistoryReply struct {
	// History is a list of history items.
	History []HistoryItem `json:"history"`
}

HistoryReply represents the content of a history_reply message in the Jupyter protocol.

type HistoryRequest

type HistoryRequest struct {
	// Output indicates whether to return output history in the resulting dictionary.
	Output bool `json:"output"`

	// Raw indicates whether to return the raw input history (true) or the transformed input (false).
	Raw bool `json:"raw"`

	// HistAccessType can be 'range', 'tail', or 'search'.
	HistAccessType string `json:"hist_access_type"`

	// Session is a number counting up each time the kernel starts.
	// Positive session number or negative number to count back from the current session.
	Session int `json:"session"`

	// If HistAccessType is 'range', get a range of input cells.
	// Start and Stop are line (cell) numbers within that session.
	Start int `json:"start"`
	Stop  int `json:"stop"`

	// If HistAccessType is 'tail' or 'search', get the last n cells.
	N int `json:"n"`

	// If HistAccessType is 'search', get cells matching the specified glob pattern (with * and ? as wildcards).
	Pattern string `json:"pattern"`

	// If HistAccessType is 'search' and Unique is true, do not include duplicated history. Default is false.
	Unique bool `json:"unique"`
}

HistoryRequest represents the content of a history_request message in the Jupyter protocol.

type InspectReply

type InspectReply struct {
	// Status indicates whether the request succeeded ('ok') or encountered an error ('error').
	Status string `json:"status"`

	// Found is true if an object was found, false otherwise.
	Found bool `json:"found"`

	// Data is a dictionary containing information about the inspected object.
	// It can be empty if nothing is found.
	Data map[string]interface{} `json:"data"`

	// Metadata is a dictionary containing additional metadata associated with the inspection result.
	Metadata map[string]interface{} `json:"metadata"`
}

InspectReply represents the content of an inspect_reply message in the Jupyter protocol.

type IntrospectionRequest

type IntrospectionRequest struct {
	// Code is the code context in which introspection is requested.
	// This may be up to an entire multiline cell.
	Code string `json:"code"`

	// CursorPos is the cursor position within 'Code' (in Unicode characters) where inspection is requested.
	CursorPos int `json:"cursor_pos"`

	// DetailLevel is the level of detail desired.
	// In IPython, 0 is equivalent to typing 'x?' at the prompt, 1 is equivalent to 'x??'.
	// The difference is up to kernels, but in IPython, level 1 includes the source code if available.
	DetailLevel int `json:"detail_level"`
}

IntrospectionRequest represents a request for code introspection. https://jupyter-protocol.readthedocs.io/en/latest/messaging.html#introspection

type KernelState

type KernelState string

KernelState represents possible execution states for the kernel. https://jupyter-protocol.readthedocs.io/en/latest/messaging.html#kernel-status

const (
	// StateBusy indicates that the kernel is currently busy processing a request.
	StateBusy KernelState = "busy"

	// StateIdle indicates that the kernel is idle and not processing any requests.
	StateIdle KernelState = "idle"

	// StateStarting indicates that the kernel is in the starting state (published exactly once at process startup).
	StateStarting KernelState = "starting"
)

type Message

type Message struct {
	// Header contains the message header.
	Header Header `json:"header"`

	// ParentHeader contains the header from the parent message.
	ParentHeader Header `json:"parent_header"`

	// Metadata contains any metadata associated with the message.
	Metadata map[string]interface{} `json:"metadata"`

	// Content is the actual content of the message.
	// The structure depends on the message type.
	Content interface{} `json:"content"`
}

Message represents a Jupyter message structure. https://jupyter-protocol.readthedocs.io/en/latest/messaging.html#general-message-format

func (*Message) Decode

func (msg *Message) Decode(parts [][]byte, signKey []byte) (err error)

func (*Message) Encode

func (msg *Message) Encode(signKey []byte) (parts [][]byte, err error)

type RawMessage

type RawMessage struct {
	// Header contains the message header.
	Header Header `json:"header"`

	// ParentHeader contains the header from the parent message.
	ParentHeader Header `json:"parent_header"`

	// Metadata contains any metadata associated with the message.
	Metadata map[string]interface{} `json:"metadata"`

	// Content is the actual content of the message.
	// The structure depends on the message type.
	Content json.RawMessage `json:"content"`
}

RawMessage represents a Jupyter message structure. https://jupyter-protocol.readthedocs.io/en/latest/messaging.html#general-message-format

func (*RawMessage) Decode

func (msg *RawMessage) Decode(parts [][]byte, signKey []byte) error

type Status

type Status string

Status represents possible status values for reply messages. https://jupyter-protocol.readthedocs.io/en/latest/messaging.html#request-reply

const (
	// StatusOk indicates that the request was processed successfully.
	StatusOk Status = "ok"

	// StatusError indicates that the request failed due to an error.
	// Additional error information should be present in the reply.
	StatusError Status = "error"

	// StatusAbort indicates that the request is aborted.
	// Deprecated in version 5.1; kernels should send StatusError instead.
	StatusAbort Status = "abort"
)

type StatusMessage

type StatusMessage struct {
	// ExecutionState represents the state of the kernel: 'busy', 'idle', 'starting'.
	ExecutionState KernelState `json:"execution_state"`
}

StatusMessage represents the content of a status message in the Jupyter protocol.

type StreamMessage

type StreamMessage struct {
	// Name of the stream, one of 'stdout', 'stderr'.
	Name string `json:"name"`

	// Text is an arbitrary string to be written to the stream.
	Text string `json:"text"`
}

StreamMessage represents the content of a stream message in the Jupyter protocol.

type UpdateDisplayDataMessage

type UpdateDisplayDataMessage struct {
	// Data contains key/value pairs, where keys are MIME types, and values are raw data of the representation in that format.
	Data map[string]interface{} `json:"data"`

	// Metadata contains any metadata that describes the data.
	Metadata map[string]interface{} `json:"metadata"`

	// Transient contains information not to be persisted to a notebook or other environment.
	// Intended to live only during a kernel session.
	// The only transient key currently defined in Jupyter is display_id
	Transient map[string]interface{} `json:"transient"`
}

UpdateDisplayDataMessage represents the content of an update_display_data message in the Jupyter protocol.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL