Sha256: 7098bf641f966f17415bb1d9c16b8023ffd5277a4470aa81fb7b4bff789f2c19

Contents?: true

Size: 996 Bytes

Versions: 2

Compression:

Stored size: 996 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 build_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

2 entries across 2 versions & 1 rubygems

Version Path
hugging-face-0.3.1 lib/hugging_face/base_api.rb
hugging-face-0.3.0 lib/hugging_face/base_api.rb