Class: StableDiffusionRuby::Backend::Python

Inherits:
Object
  • Object
show all
Defined in:
lib/stable_diffusion_ruby/backend/python.rb

Constant Summary collapse

WORKER_SCRIPT =
"worker.py"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command, params = {}) ⇒ Python

Returns a new instance of Python.



13
14
15
16
# File 'lib/stable_diffusion_ruby/backend/python.rb', line 13

def initialize(command, params = {})
  @command = command
  @params = params
end

Instance Attribute Details

#commandObject (readonly)

Returns the value of attribute command.



11
12
13
# File 'lib/stable_diffusion_ruby/backend/python.rb', line 11

def command
  @command
end

#paramsObject (readonly)

Returns the value of attribute params.



11
12
13
# File 'lib/stable_diffusion_ruby/backend/python.rb', line 11

def params
  @params
end

Class Method Details

.health_checkObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/stable_diffusion_ruby/backend/python.rb', line 40

def self.health_check
  cfg = StableDiffusionRuby.configuration
  stdout, stderr, status = Open3.capture3(
    cfg.resolved_python_executable,
    File.join(cfg.python_dir, WORKER_SCRIPT),
    "--health"
  )

  return JSON.parse(stdout) if status.success?

  { "healthy" => false, "error" => stderr }
rescue JSON::ParserError => error
  { "healthy" => false, "error" => error.message }
end

Instance Method Details

#callObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/stable_diffusion_ruby/backend/python.rb', line 18

def call
  input = JSON.generate({ command: command, params: params })

  stdout, stderr, status = Open3.capture3(
    config.resolved_python_executable, worker_script_path,
    stdin_data: input,
    chdir: config.python_dir
  )

  unless status.success?
    StableDiffusionRuby.logger.error("PythonBackend error: #{stderr}")
    raise BackendError, "Python worker failed: #{stderr.empty? ? 'unknown error' : stderr}"
  end

  result = JSON.parse(stdout)
  raise BackendError, result["error"] if result.is_a?(Hash) && result["error"]

  result
rescue JSON::ParserError => error
  raise BackendError, "Invalid JSON from Python worker: #{error.message}"
end