Class: Rager::Mesh::Providers::Replicate

Inherits:
Abstract
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/rager/mesh/providers/replicate.rb

Instance Method Summary collapse

Instance Method Details

#mesh(image_url, options) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rager/mesh/providers/replicate.rb', line 15

def mesh(image_url, options)
  api_key = options.api_key || ENV["REPLICATE_API_KEY"]
  raise Rager::Errors::CredentialsError.new("Replicate", env_var: ["REPLICATE_API_KEY"]) if api_key.nil?

  url = "https://api.replicate.com/v1/predictions"

  headers = {
    "Authorization" => "Bearer #{api_key}",
    "Content-Type" => "application/json"
  }

  body = {
    version: options.version,
    input: {
      images: [image_url],
      texture_size: 2048,
      mesh_simplify: 0.9,
      generate_model: true,
      save_gaussian_ply: true,
      ss_sampling_steps: 38
    }
  }.tap do |b|
    b[:input][:seed] = options.seed if options.seed
  end

  request = Rager::Http::Request.new(
    url: url,
    verb: Rager::Http::Verb::Post,
    headers: headers,
    body: body.to_json,
    timeout: options.timeout || Rager.config.timeout
  )

  response = Rager.config.http_adapter.make_request(request)
  response_body = T.cast(T.must(response.body), String)

  raise Rager::Errors::HttpError.new(Rager.config.http_adapter, request.url, response.status, body: response_body) unless [200, 201, 202].include?(response.status)

  json = JSON.parse(response_body)
  json.fetch("urls").fetch("get")
rescue JSON::ParserError, KeyError => e
  raise Rager::Errors::ParseError.new(response_body || "", details: e.message)
end