web.lua 6.7 KB

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