web.lua 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. _G.TURBO_SSL = true
  2. local turbo = require 'turbo'
  3. local uuid = require 'uuid'
  4. local ffi = require 'ffi'
  5. local md5 = require 'md5'
  6. require 'pl'
  7. require './lib/portable'
  8. require './lib/LeakyReLU'
  9. local cmd = torch.CmdLine()
  10. cmd:text()
  11. cmd:text("waifu2x-api")
  12. cmd:text("Options:")
  13. cmd:option("-port", 8812, 'listen port')
  14. cmd:option("-gpu", 1, 'Device ID')
  15. cmd:option("-core", 2, 'number of CPU cores')
  16. local opt = cmd:parse(arg)
  17. cutorch.setDevice(opt.gpu)
  18. torch.setdefaulttensortype('torch.FloatTensor')
  19. torch.setnumthreads(opt.core)
  20. local iproc = require './lib/iproc'
  21. local reconstruct = require './lib/reconstruct'
  22. local image_loader = require './lib/image_loader'
  23. local MODEL_DIR = "./models/anime_style_art_rgb"
  24. local noise1_model = torch.load(path.join(MODEL_DIR, "noise1_model.t7"), "ascii")
  25. local noise2_model = torch.load(path.join(MODEL_DIR, "noise2_model.t7"), "ascii")
  26. local scale20_model = torch.load(path.join(MODEL_DIR, "scale2.0x_model.t7"), "ascii")
  27. local USE_CACHE = true
  28. local CACHE_DIR = "./cache"
  29. local MAX_NOISE_IMAGE = 2560 * 2560
  30. local MAX_SCALE_IMAGE = 1280 * 1280
  31. local CURL_OPTIONS = {
  32. request_timeout = 15,
  33. connect_timeout = 10,
  34. allow_redirects = true,
  35. max_redirects = 2
  36. }
  37. local CURL_MAX_SIZE = 2 * 1024 * 1024
  38. local BLOCK_OFFSET = 7 -- see srcnn.lua
  39. local function valid_size(x, scale)
  40. if scale == 0 then
  41. return x:size(2) * x:size(3) <= MAX_NOISE_IMAGE
  42. else
  43. return x:size(2) * x:size(3) <= MAX_SCALE_IMAGE
  44. end
  45. end
  46. local function get_image(req)
  47. local file = req:get_argument("file", "")
  48. local url = req:get_argument("url", "")
  49. local blob = nil
  50. local img = nil
  51. local alpha = nil
  52. if file and file:len() > 0 then
  53. blob = file
  54. img, alpha = image_loader.decode_float(blob)
  55. elseif url and url:len() > 0 then
  56. local res = coroutine.yield(
  57. turbo.async.HTTPClient({verify_ca=false},
  58. nil,
  59. CURL_MAX_SIZE):fetch(url, CURL_OPTIONS)
  60. )
  61. if res.code == 200 then
  62. local content_type = res.headers:get("Content-Type", true)
  63. if type(content_type) == "table" then
  64. content_type = content_type[1]
  65. end
  66. if content_type and content_type:find("image") then
  67. blob = res.body
  68. img, alpha = image_loader.decode_float(blob)
  69. end
  70. end
  71. end
  72. return img, blob, alpha
  73. end
  74. local function apply_denoise1(x)
  75. return reconstruct.image(noise1_model, x, BLOCK_OFFSET)
  76. end
  77. local function apply_denoise2(x)
  78. return reconstruct.image(noise2_model, x, BLOCK_OFFSET)
  79. end
  80. local function apply_scale2x(x)
  81. return reconstruct.scale(scale20_model, 2.0, x, BLOCK_OFFSET)
  82. end
  83. local function cache_do(cache, x, func)
  84. if path.exists(cache) then
  85. return image.load(cache)
  86. else
  87. x = func(x)
  88. image.save(cache, x)
  89. return x
  90. end
  91. end
  92. local function client_disconnected(handler)
  93. return not(handler.request and
  94. handler.request.connection and
  95. handler.request.connection.stream and
  96. (not handler.request.connection.stream:closed()))
  97. end
  98. local APIHandler = class("APIHandler", turbo.web.RequestHandler)
  99. function APIHandler:post()
  100. if client_disconnected(self) then
  101. self:set_status(400)
  102. self:write("client disconnected")
  103. return
  104. end
  105. local x, src, alpha = get_image(self)
  106. local scale = tonumber(self:get_argument("scale", "0"))
  107. local noise = tonumber(self:get_argument("noise", "0"))
  108. if x and valid_size(x, scale) then
  109. if USE_CACHE and (noise ~= 0 or scale ~= 0) then
  110. local hash = md5.sumhexa(src)
  111. local cache_noise1 = path.join(CACHE_DIR, hash .. "_noise1.png")
  112. local cache_noise2 = path.join(CACHE_DIR, hash .. "_noise2.png")
  113. local cache_scale = path.join(CACHE_DIR, hash .. "_scale.png")
  114. local cache_noise1_scale = path.join(CACHE_DIR, hash .. "_noise1_scale.png")
  115. local cache_noise2_scale = path.join(CACHE_DIR, hash .. "_noise2_scale.png")
  116. if noise == 1 then
  117. x = cache_do(cache_noise1, x, apply_denoise1)
  118. elseif noise == 2 then
  119. x = cache_do(cache_noise2, x, apply_denoise2)
  120. end
  121. if scale == 1 or scale == 2 then
  122. if noise == 1 then
  123. x = cache_do(cache_noise1_scale, x, apply_scale2x)
  124. elseif noise == 2 then
  125. x = cache_do(cache_noise2_scale, x, apply_scale2x)
  126. else
  127. x = cache_do(cache_scale, x, apply_scale2x)
  128. end
  129. if scale == 1 then
  130. x = iproc.scale(x,
  131. math.floor(x:size(3) * (1.6 / 2.0) + 0.5),
  132. math.floor(x:size(2) * (1.6 / 2.0) + 0.5),
  133. "Jinc")
  134. end
  135. end
  136. elseif noise ~= 0 or scale ~= 0 then
  137. if noise == 1 then
  138. x = apply_denoise1(x)
  139. elseif noise == 2 then
  140. x = apply_denoise2(x)
  141. end
  142. if scale == 1 then
  143. local x16 = {math.floor(x:size(3) * 1.6 + 0.5), math.floor(x:size(2) * 1.6 + 0.5)}
  144. x = apply_scale2x(x)
  145. x = iproc.scale(x, x16[1], x16[2], "Jinc")
  146. elseif scale == 2 then
  147. x = apply_scale2x(x)
  148. end
  149. end
  150. local name = uuid() .. ".png"
  151. local blob, len = image_loader.encode_png(x, alpha)
  152. self:set_header("Content-Disposition", string.format('filename="%s"', name))
  153. self:set_header("Content-Type", "image/png")
  154. self:set_header("Content-Length", string.format("%d", len))
  155. self:write(ffi.string(blob, len))
  156. else
  157. if not x then
  158. self:set_status(400)
  159. self:write("ERROR: unsupported image format.")
  160. else
  161. self:set_status(400)
  162. self:write("ERROR: image size exceeds maximum allowable size.")
  163. end
  164. end
  165. collectgarbage()
  166. end
  167. local FormHandler = class("FormHandler", turbo.web.RequestHandler)
  168. local index_ja = file.read("./assets/index.ja.html")
  169. local index_en = file.read("./assets/index.html")
  170. function FormHandler:get()
  171. local lang = self.request.headers:get("Accept-Language")
  172. if lang then
  173. local langs = utils.split(lang, ",")
  174. for i = 1, #langs do
  175. langs[i] = utils.split(langs[i], ";")[1]
  176. end
  177. if langs[1] == "ja" then
  178. self:write(index_ja)
  179. else
  180. self:write(index_en)
  181. end
  182. else
  183. self:write(index_en)
  184. end
  185. end
  186. local app = turbo.web.Application:new(
  187. {
  188. {"^/$", FormHandler},
  189. {"^/index.html", turbo.web.StaticFileHandler, path.join("./assets", "index.html")},
  190. {"^/index.ja.html", turbo.web.StaticFileHandler, path.join("./assets", "index.ja.html")},
  191. {"^/api$", APIHandler},
  192. }
  193. )
  194. app:listen(opt.port, "0.0.0.0", {max_body_size = CURL_MAX_SIZE})
  195. turbo.ioloop.instance():start()