Sha256: 69ce3d1bf2cb6b7c0dc7dcda626c405c3ef20afb4f4b0c7b6c8dab6eb53bf7d7

Contents?: true

Size: 990 Bytes

Versions: 1

Compression:

Stored size: 990 Bytes

Contents

require 'logger'
require 'faraday'

module HuggingFace
  class BaseApi
    HTTP_SERVICE_UNAVAILABLE = 503
    JSON_CONTENT_TYPE = 'application/json'

    def initialize(api_token:)
      @headers = {
        'Authorization' => 'Bearer ' + api_token,
        'Content-Type' => JSON_CONTENT_TYPE
      }
    end

    private

    def connection(url)
      Faraday.new(url, headers: @headers)
    end

    def request(connection:, input:)
      response = connection.post { |req| req.body = input.to_json }

      if response.success?
        return parse_response response
      else
        raise ServiceUnavailable.new response.body if response.status == HTTP_SERVICE_UNAVAILABLE
        raise Error.new response.body
      end
    end

    def parse_response(response)
      if response.headers['Content-Type'] == JSON_CONTENT_TYPE
        JSON.parse(response.body)
      else
        response.body
      end
    end

    def logger
      @logger ||= Logger.new(STDOUT)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hugging-face-0.2.0 lib/hugging_face/base_api.rb