web.lua 5.9 KB

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