web.lua 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. require 'pl'
  2. local __FILE__ = (function() return string.gsub(debug.getinfo(2, 'S').source, "^@", "") end)()
  3. local ROOT = path.dirname(__FILE__)
  4. package.path = path.join(ROOT, "lib", "?.lua;") .. package.path
  5. _G.TURBO_SSL = true
  6. require 'w2nn'
  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 alpha_util = require 'alpha_util'
  14. local gm = require 'graphicsmagick'
  15. -- Note: turbo and xlua has different implementation of string:split().
  16. -- Therefore, string:split() has conflict issue.
  17. -- In this script, use turbo's string:split().
  18. local turbo = require 'turbo'
  19. local cmd = torch.CmdLine()
  20. cmd:text()
  21. cmd:text("waifu2x-api")
  22. cmd:text("Options:")
  23. cmd:option("-port", 8812, 'listen port')
  24. cmd:option("-gpu", 1, 'Device ID')
  25. cmd:option("-thread", -1, 'number of CPU threads')
  26. local opt = cmd:parse(arg)
  27. cutorch.setDevice(opt.gpu)
  28. torch.setdefaulttensortype('torch.FloatTensor')
  29. if opt.thread > 0 then
  30. torch.setnumthreads(opt.thread)
  31. end
  32. if cudnn then
  33. cudnn.fastest = true
  34. cudnn.benchmark = false
  35. end
  36. local ART_MODEL_DIR = path.join(ROOT, "models", "anime_style_art_rgb")
  37. local PHOTO_MODEL_DIR = path.join(ROOT, "models", "photo")
  38. local art_noise1_model = torch.load(path.join(ART_MODEL_DIR, "noise1_model.t7"), "ascii")
  39. local art_noise2_model = torch.load(path.join(ART_MODEL_DIR, "noise2_model.t7"), "ascii")
  40. local art_scale2_model = torch.load(path.join(ART_MODEL_DIR, "scale2.0x_model.t7"), "ascii")
  41. local photo_scale2_model = torch.load(path.join(PHOTO_MODEL_DIR, "scale2.0x_model.t7"), "ascii")
  42. local photo_noise1_model = torch.load(path.join(PHOTO_MODEL_DIR, "noise1_model.t7"), "ascii")
  43. local photo_noise2_model = torch.load(path.join(PHOTO_MODEL_DIR, "noise2_model.t7"), "ascii")
  44. local CLEANUP_MODEL = false -- if you are using the low memory GPU, you could use this flag.
  45. local CACHE_DIR = path.join(ROOT, "cache")
  46. local MAX_NOISE_IMAGE = 2560 * 2560
  47. local MAX_SCALE_IMAGE = 1280 * 1280
  48. local CURL_OPTIONS = {
  49. request_timeout = 60,
  50. connect_timeout = 60,
  51. allow_redirects = true,
  52. max_redirects = 2
  53. }
  54. local CURL_MAX_SIZE = 3 * 1024 * 1024
  55. local function valid_size(x, scale)
  56. if scale == 0 then
  57. return x:size(2) * x:size(3) <= MAX_NOISE_IMAGE
  58. else
  59. return x:size(2) * x:size(3) <= MAX_SCALE_IMAGE
  60. end
  61. end
  62. local function cache_url(url)
  63. local hash = md5.sumhexa(url)
  64. local cache_file = path.join(CACHE_DIR, "url_" .. hash)
  65. if path.exists(cache_file) then
  66. return image_loader.load_float(cache_file)
  67. else
  68. local res = coroutine.yield(
  69. turbo.async.HTTPClient({verify_ca=false},
  70. nil,
  71. CURL_MAX_SIZE):fetch(url, CURL_OPTIONS)
  72. )
  73. if res.code == 200 then
  74. local content_type = res.headers:get("Content-Type", true)
  75. if type(content_type) == "table" then
  76. content_type = content_type[1]
  77. end
  78. if content_type and content_type:find("image") then
  79. local fp = io.open(cache_file, "wb")
  80. local blob = res.body
  81. fp:write(blob)
  82. fp:close()
  83. return image_loader.decode_float(blob)
  84. end
  85. end
  86. end
  87. return nil, nil, nil
  88. end
  89. local function get_image(req)
  90. local file = req:get_argument("file", "")
  91. local url = req:get_argument("url", "")
  92. if file and file:len() > 0 then
  93. return image_loader.decode_float(file)
  94. elseif url and url:len() > 0 then
  95. return cache_url(url)
  96. end
  97. return nil, nil, nil
  98. end
  99. local function cleanup_model(model)
  100. if CLEANUP_MODEL then
  101. w2nn.cleanup_model(model) -- release GPU memory
  102. end
  103. end
  104. local function convert(x, alpha, options)
  105. local cache_file = path.join(CACHE_DIR, options.prefix .. ".png")
  106. local alpha_cache_file = path.join(CACHE_DIR, options.alpha_prefix .. ".png")
  107. local alpha_orig = alpha
  108. if path.exists(alpha_cache_file) then
  109. alpha = image_loader.load_float(alpha_cache_file)
  110. if alpha:dim() == 2 then
  111. alpha = alpha:reshape(1, alpha:size(1), alpha:size(2))
  112. end
  113. if alpha:size(1) == 3 then
  114. alpha = image.rgb2y(alpha)
  115. end
  116. end
  117. if path.exists(cache_file) then
  118. x = image_loader.load_float(cache_file)
  119. return x, alpha
  120. else
  121. if options.style == "art" then
  122. if options.border then
  123. x = alpha_util.make_border(x, alpha_orig, reconstruct.offset_size(art_scale2_model))
  124. end
  125. if options.method == "scale" then
  126. x = reconstruct.scale(art_scale2_model, 2.0, x)
  127. if alpha then
  128. if not (alpha:size(2) == x:size(2) and alpha:size(3) == x:size(3)) then
  129. alpha = reconstruct.scale(art_scale2_model, 2.0, alpha)
  130. image_loader.save_png(alpha_cache_file, alpha)
  131. end
  132. end
  133. cleanup_model(art_scale2_model)
  134. elseif options.method == "noise1" then
  135. x = reconstruct.image(art_noise1_model, x)
  136. cleanup_model(art_noise1_model)
  137. else -- options.method == "noise2"
  138. x = reconstruct.image(art_noise2_model, x)
  139. cleanup_model(art_noise2_model)
  140. end
  141. else -- photo
  142. if options.border then
  143. x = alpha_util.make_border(x, alpha, reconstruct.offset_size(photo_scale2_model))
  144. end
  145. if options.method == "scale" then
  146. x = reconstruct.scale(photo_scale2_model, 2.0, x)
  147. if alpha then
  148. if not (alpha:size(2) == x:size(2) and alpha:size(3) == x:size(3)) then
  149. alpha = reconstruct.scale(photo_scale2_model, 2.0, alpha)
  150. image_loader.save_png(alpha_cache_file, alpha)
  151. end
  152. end
  153. cleanup_model(photo_scale2_model)
  154. elseif options.method == "noise1" then
  155. x = reconstruct.image(photo_noise1_model, x)
  156. cleanup_model(photo_noise1_model)
  157. elseif options.method == "noise2" then
  158. x = reconstruct.image(photo_noise2_model, x)
  159. cleanup_model(photo_noise2_model)
  160. end
  161. end
  162. image_loader.save_png(cache_file, x)
  163. return x, alpha
  164. end
  165. end
  166. local function client_disconnected(handler)
  167. return not(handler.request and
  168. handler.request.connection and
  169. handler.request.connection.stream and
  170. (not handler.request.connection.stream:closed()))
  171. end
  172. local APIHandler = class("APIHandler", turbo.web.RequestHandler)
  173. function APIHandler:post()
  174. if client_disconnected(self) then
  175. self:set_status(400)
  176. self:write("client disconnected")
  177. return
  178. end
  179. local x, alpha, blob = get_image(self)
  180. local scale = tonumber(self:get_argument("scale", "0"))
  181. local noise = tonumber(self:get_argument("noise", "0"))
  182. local style = self:get_argument("style", "art")
  183. local download = (self:get_argument("download", "")):len()
  184. if style ~= "art" then
  185. style = "photo" -- style must be art or photo
  186. end
  187. if x and valid_size(x, scale) then
  188. if (noise ~= 0 or scale ~= 0) then
  189. local hash = md5.sumhexa(blob)
  190. local alpha_prefix = style .. "_" .. hash .. "_alpha"
  191. local border = false
  192. if scale ~= 0 and alpha then
  193. border = true
  194. end
  195. if noise == 1 then
  196. x = convert(x, alpha, {method = "noise1", style = style,
  197. prefix = style .. "_noise1_" .. hash,
  198. alpha_prefix = alpha_prefix, border = border})
  199. border = false
  200. elseif noise == 2 then
  201. x = convert(x, alpha, {method = "noise2", style = style,
  202. prefix = style .. "_noise2_" .. hash,
  203. alpha_prefix = alpha_prefix, border = border})
  204. border = false
  205. end
  206. if scale == 1 or scale == 2 then
  207. local prefix
  208. if noise == 1 then
  209. prefix = style .. "_noise1_scale_" .. hash
  210. elseif noise == 2 then
  211. prefix = style .. "_noise2_scale_" .. hash
  212. else
  213. prefix = style .. "_scale_" .. hash
  214. end
  215. x, alpha = convert(x, alpha, {method = "scale", style = style, prefix = prefix, alpha_prefix = alpha_prefix, border = border})
  216. if scale == 1 then
  217. x = iproc.scale(x, x:size(3) * (1.6 / 2.0), x:size(2) * (1.6 / 2.0), "Sinc")
  218. end
  219. end
  220. end
  221. local name = uuid() .. ".png"
  222. local blob = image_loader.encode_png(alpha_util.composite(x, alpha))
  223. self:set_header("Content-Length", string.format("%d", #blob))
  224. if download > 0 then
  225. self:set_header("Content-Type", "application/octet-stream")
  226. self:set_header("Content-Disposition", string.format('attachment; filename="%s"', name))
  227. else
  228. self:set_header("Content-Type", "image/png")
  229. self:set_header("Content-Disposition", string.format('inline; filename="%s"', name))
  230. end
  231. self:write(blob)
  232. else
  233. if not x then
  234. self:set_status(400)
  235. self:write("ERROR: An error occurred. (unsupported image format/connection timeout/file is too large)")
  236. else
  237. self:set_status(400)
  238. self:write("ERROR: image size exceeds maximum allowable size.")
  239. end
  240. end
  241. collectgarbage()
  242. end
  243. local FormHandler = class("FormHandler", turbo.web.RequestHandler)
  244. local index_ja = file.read(path.join(ROOT, "assets", "index.ja.html"))
  245. local index_ru = file.read(path.join(ROOT, "assets", "index.ru.html"))
  246. local index_pt = file.read(path.join(ROOT, "assets", "index.pt.html"))
  247. local index_es = file.read(path.join(ROOT, "assets", "index.es.html"))
  248. local index_en = file.read(path.join(ROOT, "assets", "index.html"))
  249. function FormHandler:get()
  250. local lang = self.request.headers:get("Accept-Language")
  251. if lang then
  252. local langs = utils.split(lang, ",")
  253. for i = 1, #langs do
  254. langs[i] = utils.split(langs[i], ";")[1]
  255. end
  256. if langs[1] == "ja" then
  257. self:write(index_ja)
  258. elseif langs[1] == "ru" then
  259. self:write(index_ru)
  260. elseif langs[1] == "pt" or langs[1] == "pt-BR" then
  261. self:write(index_pt)
  262. elseif langs[1] == "es" or langs[1] == "es-ES" then
  263. self:write(index_es)
  264. else
  265. self:write(index_en)
  266. end
  267. else
  268. self:write(index_en)
  269. end
  270. end
  271. turbo.log.categories = {
  272. ["success"] = true,
  273. ["notice"] = false,
  274. ["warning"] = true,
  275. ["error"] = true,
  276. ["debug"] = false,
  277. ["development"] = false
  278. }
  279. local app = turbo.web.Application:new(
  280. {
  281. {"^/$", FormHandler},
  282. {"^/api$", APIHandler},
  283. {"^/([%a%d%.%-_]+)$", turbo.web.StaticFileHandler, path.join(ROOT, "assets/")},
  284. }
  285. )
  286. app:listen(opt.port, "0.0.0.0", {max_body_size = CURL_MAX_SIZE})
  287. turbo.ioloop.instance():start()