Class: RubyAmazonBedrock::ResponseBuilders::AmazonImage

Inherits:
Object
  • Object
show all
Defined in:
lib/bedrock_runtime/response_builders/amazon_image.rb

Overview

The AmazonImage class is responsible for handling and processing image data received in a response. It parses the response, extracts the image data, decodes it from Base64, and saves it as a file.

Instance Method Summary collapse

Constructor Details

#initialize(response, options = {}) ⇒ AmazonImage

Initializes a new instance of the AmazonImage class.

The response should contain the image data in Base64 format. the location and name of the file to save the image. Default is ‘image.jpg’.

Parameters:

  • response (Object)

    The raw response object which is an HTTP response.

  • options (Hash) (defaults to: {})

    Optional parameters, currently supporting :file_path for specifying



18
19
20
21
22
# File 'lib/bedrock_runtime/response_builders/amazon_image.rb', line 18

def initialize(response, options = {})
  @response = response
  @file_path = options[:file_path] || 'image.jpg'
  @upload = options[:upload] || false
end

Instance Method Details

#buildHash

Processes the response to extract and decode image data, then saves it as a file. This method parses the response body as JSON, extracts the first artifact which is expected to be an image in Base64 format, decodes it, and writes it to a file. If the operation is successful, a hash with a success status and file path is returned. If an error occurs, a hash with a failure status and error details is returned.

If successful, the hash includes :result set to :success and :file_path. If upload option is provided it will also include :s3_url after saving the image in S3. If failure, the hash includes :result set to :failure and :error with exception details.

Returns:

  • (Hash)

    A hash indicating the result of the operation.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/bedrock_runtime/response_builders/amazon_image.rb', line 34

def build
  response_object = JSON.parse(@response.body.read, symbolize_names: true)
  image_data = Base64.decode64(response_object[:artifacts].first[:base64])
  File.binwrite(@file_path, image_data)

  upload_image if can_upload?

  {
    result: :success,
    file_path: @file_path,
    s3_url: s3_url
  }.compact
rescue StandardError => e
  {
    result: :failure,
    error: e
  }
end