web.lua 5.9 KB

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