web.lua 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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_scale2_model = torch.load(path.join(ART_MODEL_DIR, "scale2.0x_model.t7"), "ascii")
  39. local art_noise1_model = torch.load(path.join(ART_MODEL_DIR, "noise1_model.t7"), "ascii")
  40. local art_noise2_model = torch.load(path.join(ART_MODEL_DIR, "noise2_model.t7"), "ascii")
  41. local art_noise3_model = torch.load(path.join(ART_MODEL_DIR, "noise3_model.t7"), "ascii")
  42. local photo_scale2_model = torch.load(path.join(PHOTO_MODEL_DIR, "scale2.0x_model.t7"), "ascii")
  43. local photo_noise1_model = torch.load(path.join(PHOTO_MODEL_DIR, "noise1_model.t7"), "ascii")
  44. local photo_noise2_model = torch.load(path.join(PHOTO_MODEL_DIR, "noise2_model.t7"), "ascii")
  45. local photo_noise3_model = torch.load(path.join(PHOTO_MODEL_DIR, "noise3_model.t7"), "ascii")
  46. local CLEANUP_MODEL = false -- if you are using the low memory GPU, you could use this flag.
  47. local CACHE_DIR = path.join(ROOT, "cache")
  48. local MAX_NOISE_IMAGE = 2560 * 2560
  49. local MAX_SCALE_IMAGE = 1280 * 1280
  50. local CURL_OPTIONS = {
  51. request_timeout = 60,
  52. connect_timeout = 60,
  53. allow_redirects = true,
  54. max_redirects = 2
  55. }
  56. local CURL_MAX_SIZE = 3 * 1024 * 1024
  57. local function valid_size(x, scale)
  58. if scale == 0 then
  59. return x:size(2) * x:size(3) <= MAX_NOISE_IMAGE
  60. else
  61. return x:size(2) * x:size(3) <= MAX_SCALE_IMAGE
  62. end
  63. end
  64. local function cache_url(url)
  65. local hash = md5.sumhexa(url)
  66. local cache_file = path.join(CACHE_DIR, "url_" .. hash)
  67. if path.exists(cache_file) then
  68. return image_loader.load_float(cache_file)
  69. else
  70. local res = coroutine.yield(
  71. turbo.async.HTTPClient({verify_ca=false},
  72. nil,
  73. CURL_MAX_SIZE):fetch(url, CURL_OPTIONS)
  74. )
  75. if res.code == 200 then
  76. local content_type = res.headers:get("Content-Type", true)
  77. if type(content_type) == "table" then
  78. content_type = content_type[1]
  79. end
  80. if content_type and content_type:find("image") then
  81. local fp = io.open(cache_file, "wb")
  82. local blob = res.body
  83. fp:write(blob)
  84. fp:close()
  85. return image_loader.decode_float(blob)
  86. end
  87. end
  88. end
  89. return nil, nil, nil
  90. end
  91. local function get_image(req)
  92. local file_info = req:get_arguments("file")
  93. local url = req:get_argument("url", "")
  94. local file = nil
  95. local filename = nil
  96. if file_info and #file_info == 1 then
  97. file = file_info[1][1]
  98. local disp = file_info[1]["content-disposition"]
  99. if disp and disp["filename"] then
  100. filename = path.basename(disp["filename"])
  101. end
  102. end
  103. if file and file:len() > 0 then
  104. local x, alpha, blob = image_loader.decode_float(file)
  105. return x, alpha, blob, filename
  106. elseif url and url:len() > 0 then
  107. local x, alpha, blob = cache_url(url)
  108. return x, alpha, blob, filename
  109. end
  110. return nil, nil, nil, nil
  111. end
  112. local function cleanup_model(model)
  113. if CLEANUP_MODEL then
  114. model:clearState() -- release GPU memory
  115. end
  116. end
  117. local function convert(x, alpha, options)
  118. local cache_file = path.join(CACHE_DIR, options.prefix .. ".png")
  119. local alpha_cache_file = path.join(CACHE_DIR, options.alpha_prefix .. ".png")
  120. local alpha_orig = alpha
  121. if path.exists(alpha_cache_file) then
  122. alpha = image_loader.load_float(alpha_cache_file)
  123. if alpha:dim() == 2 then
  124. alpha = alpha:reshape(1, alpha:size(1), alpha:size(2))
  125. end
  126. if alpha:size(1) == 3 then
  127. alpha = image.rgb2y(alpha)
  128. end
  129. end
  130. if path.exists(cache_file) then
  131. x = image_loader.load_float(cache_file)
  132. return x, alpha
  133. else
  134. if options.style == "art" then
  135. if options.border then
  136. x = alpha_util.make_border(x, alpha_orig, reconstruct.offset_size(art_scale2_model))
  137. end
  138. if options.method == "scale" then
  139. x = reconstruct.scale(art_scale2_model, 2.0, x)
  140. if alpha then
  141. if not (alpha:size(2) == x:size(2) and alpha:size(3) == x:size(3)) then
  142. alpha = reconstruct.scale(art_scale2_model, 2.0, alpha)
  143. image_loader.save_png(alpha_cache_file, alpha)
  144. end
  145. end
  146. cleanup_model(art_scale2_model)
  147. elseif options.method == "noise1" then
  148. x = reconstruct.image(art_noise1_model, x)
  149. cleanup_model(art_noise1_model)
  150. elseif options.method == "noise2" then
  151. x = reconstruct.image(art_noise2_model, x)
  152. cleanup_model(art_noise2_model)
  153. elseif options.method == "noise3" then
  154. x = reconstruct.image(art_noise3_model, x)
  155. cleanup_model(art_noise3_model)
  156. end
  157. else -- photo
  158. if options.border then
  159. x = alpha_util.make_border(x, alpha, reconstruct.offset_size(photo_scale2_model))
  160. end
  161. if options.method == "scale" then
  162. x = reconstruct.scale(photo_scale2_model, 2.0, x)
  163. if alpha then
  164. if not (alpha:size(2) == x:size(2) and alpha:size(3) == x:size(3)) then
  165. alpha = reconstruct.scale(photo_scale2_model, 2.0, alpha)
  166. image_loader.save_png(alpha_cache_file, alpha)
  167. end
  168. end
  169. cleanup_model(photo_scale2_model)
  170. elseif options.method == "noise1" then
  171. x = reconstruct.image(photo_noise1_model, x)
  172. cleanup_model(photo_noise1_model)
  173. elseif options.method == "noise2" then
  174. x = reconstruct.image(photo_noise2_model, x)
  175. cleanup_model(photo_noise2_model)
  176. elseif options.method == "noise3" then
  177. x = reconstruct.image(photo_noise3_model, x)
  178. cleanup_model(photo_noise3_model)
  179. end
  180. end
  181. image_loader.save_png(cache_file, x)
  182. return x, alpha
  183. end
  184. end
  185. local function client_disconnected(handler)
  186. return not(handler.request and
  187. handler.request.connection and
  188. handler.request.connection.stream and
  189. (not handler.request.connection.stream:closed()))
  190. end
  191. local function make_output_filename(filename, mode)
  192. local e = path.extension(filename)
  193. local base = filename:sub(0, filename:len() - e:len())
  194. if mode then
  195. return base .. "_waifu2x_" .. mode .. ".png"
  196. else
  197. return base .. ".png"
  198. end
  199. end
  200. local APIHandler = class("APIHandler", turbo.web.RequestHandler)
  201. function APIHandler:post()
  202. if client_disconnected(self) then
  203. self:set_status(400)
  204. self:write("client disconnected")
  205. return
  206. end
  207. local x, alpha, blob, filename = get_image(self)
  208. local scale = tonumber(self:get_argument("scale", "0"))
  209. local noise = tonumber(self:get_argument("noise", "0"))
  210. local style = self:get_argument("style", "art")
  211. local download = (self:get_argument("download", "")):len()
  212. if style ~= "art" then
  213. style = "photo" -- style must be art or photo
  214. end
  215. if x and valid_size(x, scale) then
  216. local prefix = nil
  217. if (noise ~= 0 or scale ~= 0) then
  218. local hash = md5.sumhexa(blob)
  219. local alpha_prefix = style .. "_" .. hash .. "_alpha"
  220. local border = false
  221. if scale ~= 0 and alpha then
  222. border = true
  223. end
  224. if noise == 1 then
  225. prefix = style .. "_noise1_"
  226. x = convert(x, alpha, {method = "noise1", style = style,
  227. prefix = prefix .. hash,
  228. alpha_prefix = alpha_prefix, border = border})
  229. border = false
  230. elseif noise == 2 then
  231. prefix = style .. "_noise2_"
  232. x = convert(x, alpha, {method = "noise2", style = style,
  233. prefix = prefix .. hash,
  234. alpha_prefix = alpha_prefix, border = border})
  235. border = false
  236. elseif noise == 3 then
  237. prefix = style .. "_noise3_"
  238. x = convert(x, alpha, {method = "noise3", style = style,
  239. prefix = prefix .. hash,
  240. alpha_prefix = alpha_prefix, border = border})
  241. border = false
  242. end
  243. if scale == 1 or scale == 2 then
  244. if noise == 1 then
  245. prefix = style .. "_noise1_scale_"
  246. elseif noise == 2 then
  247. prefix = style .. "_noise2_scale_"
  248. elseif noise == 3 then
  249. prefix = style .. "_noise3_scale_"
  250. else
  251. prefix = style .. "_scale_"
  252. end
  253. x, alpha = convert(x, alpha, {method = "scale", style = style, prefix = prefix .. hash, alpha_prefix = alpha_prefix, border = border})
  254. if scale == 1 then
  255. x = iproc.scale(x, x:size(3) * (1.6 / 2.0), x:size(2) * (1.6 / 2.0), "Sinc")
  256. end
  257. end
  258. end
  259. local name = nil
  260. if filename then
  261. if prefix then
  262. name = make_output_filename(filename, prefix:sub(0, prefix:len()-1))
  263. else
  264. name = make_output_filename(filename, nil)
  265. end
  266. else
  267. name = uuid() .. ".png"
  268. end
  269. local blob = image_loader.encode_png(alpha_util.composite(x, alpha), 8, true)
  270. self:set_header("Content-Length", string.format("%d", #blob))
  271. if download > 0 then
  272. self:set_header("Content-Type", "application/octet-stream")
  273. self:set_header("Content-Disposition", string.format('attachment; filename="%s"', name))
  274. else
  275. self:set_header("Content-Type", "image/png")
  276. self:set_header("Content-Disposition", string.format('inline; filename="%s"', name))
  277. end
  278. self:write(blob)
  279. else
  280. if not x then
  281. self:set_status(400)
  282. self:write("ERROR: An error occurred. (unsupported image format/connection timeout/file is too large)")
  283. else
  284. self:set_status(400)
  285. self:write("ERROR: image size exceeds maximum allowable size.")
  286. end
  287. end
  288. collectgarbage()
  289. end
  290. local FormHandler = class("FormHandler", turbo.web.RequestHandler)
  291. local index_ja = file.read(path.join(ROOT, "assets", "index.ja.html"))
  292. local index_ru = file.read(path.join(ROOT, "assets", "index.ru.html"))
  293. local index_pt = file.read(path.join(ROOT, "assets", "index.pt.html"))
  294. local index_es = file.read(path.join(ROOT, "assets", "index.es.html"))
  295. local index_fr = file.read(path.join(ROOT, "assets", "index.fr.html"))
  296. local index_en = file.read(path.join(ROOT, "assets", "index.html"))
  297. function FormHandler:get()
  298. local lang = self.request.headers:get("Accept-Language")
  299. if lang then
  300. local langs = utils.split(lang, ",")
  301. for i = 1, #langs do
  302. langs[i] = utils.split(langs[i], ";")[1]
  303. end
  304. if langs[1] == "ja" then
  305. self:write(index_ja)
  306. elseif langs[1] == "ru" then
  307. self:write(index_ru)
  308. elseif langs[1] == "pt" or langs[1] == "pt-BR" then
  309. self:write(index_pt)
  310. elseif langs[1] == "es" or langs[1] == "es-ES" then
  311. self:write(index_es)
  312. elseif langs[1] == "fr" then
  313. self:write(index_fr)
  314. else
  315. self:write(index_en)
  316. end
  317. else
  318. self:write(index_en)
  319. end
  320. end
  321. turbo.log.categories = {
  322. ["success"] = true,
  323. ["notice"] = false,
  324. ["warning"] = true,
  325. ["error"] = true,
  326. ["debug"] = false,
  327. ["development"] = false
  328. }
  329. local app = turbo.web.Application:new(
  330. {
  331. {"^/$", FormHandler},
  332. {"^/api$", APIHandler},
  333. {"^/([%a%d%.%-_]+)$", turbo.web.StaticFileHandler, path.join(ROOT, "assets/")},
  334. }
  335. )
  336. app:listen(opt.port, "0.0.0.0", {max_body_size = CURL_MAX_SIZE})
  337. turbo.ioloop.instance():start()