Sha256: 398d198b6e0bc69c60ac6719d8e87590e5b9e458b9f79d1c62c3dbc5024097ba

Contents?: true

Size: 1011 Bytes

Versions: 3

Compression:

Stored size: 1011 Bytes

Contents

require 'json'
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

3 entries across 3 versions & 1 rubygems

Version Path
hugging-face-0.3.4 lib/hugging_face/base_api.rb
hugging-face-0.3.3 lib/hugging_face/base_api.rb
hugging-face-0.3.2 lib/hugging_face/base_api.rb