Sha256: e989d95e5e17a732f0dad56d96788a3dd5fc75f7ad75219505af13f654fe4d19

Contents?: true

Size: 1.06 KB

Versions: 1

Compression:

Stored size: 1.06 KB

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:, params: nil)
      response = connection.post { |req| 
        req.body = input.to_json 
        req.params = params if params
      }
      
      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.3.5 lib/hugging_face/base_api.rb