web.lua 6.0 KB

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