web.lua 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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_info = req:get_arguments("file")
  91. local url = req:get_argument("url", "")
  92. local file = nil
  93. local filename = nil
  94. if file_info and #file_info == 1 then
  95. file = file_info[1][1]
  96. local disp = file_info[1]["content-disposition"]
  97. if disp and disp["filename"] then
  98. filename = path.basename(disp["filename"])
  99. end
  100. end
  101. if file and file:len() > 0 then
  102. local x, alpha, blob = image_loader.decode_float(file)
  103. return x, alpha, blob, filename
  104. elseif url and url:len() > 0 then
  105. local x, alpha, blob = cache_url(url)
  106. return x, alpha, blob, filename
  107. end
  108. return nil, nil, nil, nil
  109. end
  110. local function cleanup_model(model)
  111. if CLEANUP_MODEL then
  112. w2nn.cleanup_model(model) -- release GPU memory
  113. end
  114. end
  115. local function convert(x, alpha, options)
  116. local cache_file = path.join(CACHE_DIR, options.prefix .. ".png")
  117. local alpha_cache_file = path.join(CACHE_DIR, options.alpha_prefix .. ".png")
  118. local alpha_orig = alpha
  119. if path.exists(alpha_cache_file) then
  120. alpha = image_loader.load_float(alpha_cache_file)
  121. if alpha:dim() == 2 then
  122. alpha = alpha:reshape(1, alpha:size(1), alpha:size(2))
  123. end
  124. if alpha:size(1) == 3 then
  125. alpha = image.rgb2y(alpha)
  126. end
  127. end
  128. if path.exists(cache_file) then
  129. x = image_loader.load_float(cache_file)
  130. return x, alpha
  131. else
  132. if options.style == "art" then
  133. if options.border then
  134. x = alpha_util.make_border(x, alpha_orig, reconstruct.offset_size(art_scale2_model))
  135. end
  136. if options.method == "scale" then
  137. x = reconstruct.scale(art_scale2_model, 2.0, x)
  138. if alpha then
  139. if not (alpha:size(2) == x:size(2) and alpha:size(3) == x:size(3)) then
  140. alpha = reconstruct.scale(art_scale2_model, 2.0, alpha)
  141. image_loader.save_png(alpha_cache_file, alpha)
  142. end
  143. end
  144. cleanup_model(art_scale2_model)
  145. elseif options.method == "noise1" then
  146. x = reconstruct.image(art_noise1_model, x)
  147. cleanup_model(art_noise1_model)
  148. else -- options.method == "noise2"
  149. x = reconstruct.image(art_noise2_model, x)
  150. cleanup_model(art_noise2_model)
  151. end
  152. else -- photo
  153. if options.border then
  154. x = alpha_util.make_border(x, alpha, reconstruct.offset_size(photo_scale2_model))
  155. end
  156. if options.method == "scale" then
  157. x = reconstruct.scale(photo_scale2_model, 2.0, x)
  158. if alpha then
  159. if not (alpha:size(2) == x:size(2) and alpha:size(3) == x:size(3)) then
  160. alpha = reconstruct.scale(photo_scale2_model, 2.0, alpha)
  161. image_loader.save_png(alpha_cache_file, alpha)
  162. end
  163. end
  164. cleanup_model(photo_scale2_model)
  165. elseif options.method == "noise1" then
  166. x = reconstruct.image(photo_noise1_model, x)
  167. cleanup_model(photo_noise1_model)
  168. elseif options.method == "noise2" then
  169. x = reconstruct.image(photo_noise2_model, x)
  170. cleanup_model(photo_noise2_model)
  171. end
  172. end
  173. image_loader.save_png(cache_file, x)
  174. return x, alpha
  175. end
  176. end
  177. local function client_disconnected(handler)
  178. return not(handler.request and
  179. handler.request.connection and
  180. handler.request.connection.stream and
  181. (not handler.request.connection.stream:closed()))
  182. end
  183. local function make_output_filename(filename, mode)
  184. local e = path.extension(filename)
  185. local base = filename:sub(0, filename:len() - e:len())
  186. if mode then
  187. return base .. "_waifu2x_" .. mode .. ".png"
  188. else
  189. return base .. ".png"
  190. end
  191. end
  192. local APIHandler = class("APIHandler", turbo.web.RequestHandler)
  193. function APIHandler:post()
  194. if client_disconnected(self) then
  195. self:set_status(400)
  196. self:write("client disconnected")
  197. return
  198. end
  199. local x, alpha, blob, filename = get_image(self)
  200. local scale = tonumber(self:get_argument("scale", "0"))
  201. local noise = tonumber(self:get_argument("noise", "0"))
  202. local style = self:get_argument("style", "art")
  203. local download = (self:get_argument("download", "")):len()
  204. if style ~= "art" then
  205. style = "photo" -- style must be art or photo
  206. end
  207. if x and valid_size(x, scale) then
  208. local prefix = nil
  209. if (noise ~= 0 or scale ~= 0) then
  210. local hash = md5.sumhexa(blob)
  211. local alpha_prefix = style .. "_" .. hash .. "_alpha"
  212. local border = false
  213. if scale ~= 0 and alpha then
  214. border = true
  215. end
  216. if noise == 1 then
  217. prefix = style .. "_noise1_"
  218. x = convert(x, alpha, {method = "noise1", style = style,
  219. prefix = prefix .. hash,
  220. alpha_prefix = alpha_prefix, border = border})
  221. border = false
  222. elseif noise == 2 then
  223. prefix = style .. "_noise1_"
  224. x = convert(x, alpha, {method = "noise2", style = style,
  225. prefix = prefix .. hash,
  226. alpha_prefix = alpha_prefix, border = border})
  227. border = false
  228. end
  229. if scale == 1 or scale == 2 then
  230. if noise == 1 then
  231. prefix = style .. "_noise1_scale_"
  232. elseif noise == 2 then
  233. prefix = style .. "_noise2_scale_"
  234. else
  235. prefix = style .. "_scale_"
  236. end
  237. x, alpha = convert(x, alpha, {method = "scale", style = style, prefix = prefix .. hash, alpha_prefix = alpha_prefix, border = border})
  238. if scale == 1 then
  239. x = iproc.scale(x, x:size(3) * (1.6 / 2.0), x:size(2) * (1.6 / 2.0), "Sinc")
  240. end
  241. end
  242. end
  243. local name = nil
  244. if filename then
  245. if prefix then
  246. name = make_output_filename(filename, prefix:sub(0, prefix:len()-1))
  247. else
  248. name = make_output_filename(filename, nil)
  249. end
  250. else
  251. name = uuid() .. ".png"
  252. end
  253. local blob = image_loader.encode_png(alpha_util.composite(x, alpha))
  254. self:set_header("Content-Length", string.format("%d", #blob))
  255. if download > 0 then
  256. self:set_header("Content-Type", "application/octet-stream")
  257. self:set_header("Content-Disposition", string.format('attachment; filename="%s"', name))
  258. else
  259. self:set_header("Content-Type", "image/png")
  260. self:set_header("Content-Disposition", string.format('inline; filename="%s"', name))
  261. end
  262. self:write(blob)
  263. else
  264. if not x then
  265. self:set_status(400)
  266. self:write("ERROR: An error occurred. (unsupported image format/connection timeout/file is too large)")
  267. else
  268. self:set_status(400)
  269. self:write("ERROR: image size exceeds maximum allowable size.")
  270. end
  271. end
  272. collectgarbage()
  273. end
  274. local FormHandler = class("FormHandler", turbo.web.RequestHandler)
  275. local index_ja = file.read(path.join(ROOT, "assets", "index.ja.html"))
  276. local index_ru = file.read(path.join(ROOT, "assets", "index.ru.html"))
  277. local index_pt = file.read(path.join(ROOT, "assets", "index.pt.html"))
  278. local index_es = file.read(path.join(ROOT, "assets", "index.es.html"))
  279. local index_fr = file.read(path.join(ROOT, "assets", "index.fr.html"))
  280. local index_en = file.read(path.join(ROOT, "assets", "index.html"))
  281. function FormHandler:get()
  282. local lang = self.request.headers:get("Accept-Language")
  283. if lang then
  284. local langs = utils.split(lang, ",")
  285. for i = 1, #langs do
  286. langs[i] = utils.split(langs[i], ";")[1]
  287. end
  288. if langs[1] == "ja" then
  289. self:write(index_ja)
  290. elseif langs[1] == "ru" then
  291. self:write(index_ru)
  292. elseif langs[1] == "pt" or langs[1] == "pt-BR" then
  293. self:write(index_pt)
  294. elseif langs[1] == "es" or langs[1] == "es-ES" then
  295. self:write(index_es)
  296. elseif langs[1] == "fr" then
  297. self:write(index_fr)
  298. else
  299. self:write(index_en)
  300. end
  301. else
  302. self:write(index_en)
  303. end
  304. end
  305. turbo.log.categories = {
  306. ["success"] = true,
  307. ["notice"] = false,
  308. ["warning"] = true,
  309. ["error"] = true,
  310. ["debug"] = false,
  311. ["development"] = false
  312. }
  313. local app = turbo.web.Application:new(
  314. {
  315. {"^/$", FormHandler},
  316. {"^/api$", APIHandler},
  317. {"^/([%a%d%.%-_]+)$", turbo.web.StaticFileHandler, path.join(ROOT, "assets/")},
  318. }
  319. )
  320. app:listen(opt.port, "0.0.0.0", {max_body_size = CURL_MAX_SIZE})
  321. turbo.ioloop.instance():start()