Module: Waifu2x
- Defined in:
- lib/waifu2x.rb,
lib/waifu2x/errors.rb,
lib/waifu2x/version.rb
Defined Under Namespace
Classes: Error, InvalidArgument, InvalidImage, ServerError
Constant Summary collapse
- USER_AGENT =
"Waifu2x Ruby Gem #{Waifu2x::VERSION}".freeze
- API_ENDPOINT =
'https://waifu2x.booru.pics'.freeze
- VERSION =
"0.3.1"
Class Method Summary collapse
-
.convert(source, output_file = nil, options = {}) ⇒ String
Converts image from a local file or remote URL.
-
.handle_request(file_or_url, options) ⇒ String
Performs request to the Waifu2x API for image conversion.
Class Method Details
.convert(source, output_file = nil, options = {}) ⇒ String
Converts image from a local file or remote URL
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/waifu2x.rb', line 19 def self.convert(source, output_file=nil, ={}) if source =~ /\A(https?|ftp):\/\//i converted_url = handle_request(source, ) else begin converted_url = handle_request(File.open(source), ) rescue Errno::ENOENT, Errno::EACCES raise InvalidImage, "Can't open image file: #{source}" end end if [:raw] converted_url else output_file = output_filename(source) if output_file.to_s.strip.empty? IO.copy_stream(open(converted_url), output_file) output_file end end |
.handle_request(file_or_url, options) ⇒ String
Performs request to the Waifu2x API for image conversion
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/waifu2x.rb', line 46 def self.handle_request(file_or_url, ) noise = [:noise] || 1 scale = [:scale] || 2 noise, scale = { followlocation: true, headers: { 'User-Agent' => USER_AGENT } } request = if file_or_url.is_a?(File) Typhoeus::Request.new( "#{API_ENDPOINT}/Home/upload", .merge( method: :post, body: { denoise: noise, scale: scale, img: file_or_url } ) ) else Typhoeus::Request.new( "#{API_ENDPOINT}/Home/fromlink", .merge( method: :get, params: { denoise: noise, scale: scale, url: file_or_url } ) ) end response = request.run if response.body.include?('File not found') || response.body.include?('Image file is not of type') || response.body.include?('Image file is too large') raise InvalidImage, response.body end if response.code != 200 raise Waifu2x::ServerError, "Request to Waifu2x API failed with response code: #{response.code}" end hash = response.effective_url.match(/hash=(\S+)/)[1] "#{API_ENDPOINT}/outfiles/#{hash}.jpg" end |