web.lua 6.7 KB

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