web.lua 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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("-crop_size", 128, 'patch size per process')
  26. cmd:option("-batch_size", 1, 'batch size')
  27. cmd:option("-thread", -1, 'number of CPU threads')
  28. cmd:option("-force_cudnn", 0, 'use cuDNN backend (0|1)')
  29. local opt = cmd:parse(arg)
  30. cutorch.setDevice(opt.gpu)
  31. torch.setdefaulttensortype('torch.FloatTensor')
  32. if opt.thread > 0 then
  33. torch.setnumthreads(opt.thread)
  34. end
  35. if cudnn then
  36. cudnn.fastest = true
  37. cudnn.benchmark = true
  38. end
  39. opt.force_cudnn = opt.force_cudnn == 1
  40. local ART_MODEL_DIR = path.join(ROOT, "models", "upconv_7", "art")
  41. local PHOTO_MODEL_DIR = path.join(ROOT, "models", "upconv_7", "photo")
  42. local art_model = {
  43. scale = w2nn.load_model(path.join(ART_MODEL_DIR, "scale2.0x_model.t7"), opt.force_cudnn),
  44. noise1_scale = w2nn.load_model(path.join(ART_MODEL_DIR, "noise1_scale2.0x_model.t7"), opt.force_cudnn),
  45. noise2_scale = w2nn.load_model(path.join(ART_MODEL_DIR, "noise2_scale2.0x_model.t7"), opt.force_cudnn),
  46. noise3_scale = w2nn.load_model(path.join(ART_MODEL_DIR, "noise3_scale2.0x_model.t7"), opt.force_cudnn),
  47. noise1 = w2nn.load_model(path.join(ART_MODEL_DIR, "noise1_model.t7"), opt.force_cudnn),
  48. noise2 = w2nn.load_model(path.join(ART_MODEL_DIR, "noise2_model.t7"), opt.force_cudnn),
  49. noise3 = w2nn.load_model(path.join(ART_MODEL_DIR, "noise3_model.t7"), opt.force_cudnn)
  50. }
  51. local photo_model = {
  52. scale = w2nn.load_model(path.join(PHOTO_MODEL_DIR, "scale2.0x_model.t7"), opt.force_cudnn),
  53. noise1_scale = w2nn.load_model(path.join(PHOTO_MODEL_DIR, "noise1_scale2.0x_model.t7"), opt.force_cudnn),
  54. noise2_scale = w2nn.load_model(path.join(PHOTO_MODEL_DIR, "noise2_scale2.0x_model.t7"), opt.force_cudnn),
  55. noise3_scale = w2nn.load_model(path.join(PHOTO_MODEL_DIR, "noise3_scale2.0x_model.t7"), opt.force_cudnn),
  56. noise1 = w2nn.load_model(path.join(PHOTO_MODEL_DIR, "noise1_model.t7"), opt.force_cudnn),
  57. noise2 = w2nn.load_model(path.join(PHOTO_MODEL_DIR, "noise2_model.t7"), opt.force_cudnn),
  58. noise3 = w2nn.load_model(path.join(PHOTO_MODEL_DIR, "noise3_model.t7"), opt.force_cudnn)
  59. }
  60. collectgarbage()
  61. local CLEANUP_MODEL = false -- if you are using the low memory GPU, you could use this flag.
  62. local CACHE_DIR = path.join(ROOT, "cache")
  63. local MAX_NOISE_IMAGE = 2560 * 2560
  64. local MAX_SCALE_IMAGE = 1280 * 1280
  65. local CURL_OPTIONS = {
  66. request_timeout = 60,
  67. connect_timeout = 60,
  68. allow_redirects = true,
  69. max_redirects = 2
  70. }
  71. local CURL_MAX_SIZE = 3 * 1024 * 1024
  72. local function valid_size(x, scale, tta_level)
  73. if scale == 0 then
  74. local limit = math.pow(math.floor(math.pow(MAX_NOISE_IMAGE / tta_level, 0.5)), 2)
  75. return x:size(2) * x:size(3) <= limit
  76. else
  77. local limit = math.pow(math.floor(math.pow(MAX_SCALE_IMAGE / tta_level, 0.5)), 2)
  78. return x:size(2) * x:size(3) <= limit
  79. end
  80. end
  81. local function auto_tta_level(x, scale)
  82. local limit2, limit4, limit8
  83. if scale == 0 then
  84. limit2 = math.pow(math.floor(math.pow(MAX_NOISE_IMAGE / 2, 0.5)), 2)
  85. limit4 = math.pow(math.floor(math.pow(MAX_NOISE_IMAGE / 4, 0.5)), 2)
  86. limit8 = math.pow(math.floor(math.pow(MAX_NOISE_IMAGE / 8, 0.5)), 2)
  87. else
  88. limit2 = math.pow(math.floor(math.pow(MAX_SCALE_IMAGE / 2, 0.5)), 2)
  89. limit4 = math.pow(math.floor(math.pow(MAX_SCALE_IMAGE / 4, 0.5)), 2)
  90. limit8 = math.pow(math.floor(math.pow(MAX_SCALE_IMAGE / 8, 0.5)), 2)
  91. end
  92. local px = x:size(2) * x:size(3)
  93. if px <= limit8 then
  94. return 8
  95. elseif px <= limit4 then
  96. return 4
  97. elseif px <= limit2 then
  98. return 2
  99. else
  100. return 1
  101. end
  102. end
  103. local function cache_url(url)
  104. local hash = md5.sumhexa(url)
  105. local cache_file = path.join(CACHE_DIR, "url_" .. hash)
  106. if path.exists(cache_file) then
  107. return image_loader.load_float(cache_file)
  108. else
  109. local res = coroutine.yield(
  110. turbo.async.HTTPClient({verify_ca=false},
  111. nil,
  112. CURL_MAX_SIZE):fetch(url, CURL_OPTIONS)
  113. )
  114. if res.code == 200 then
  115. local content_type = res.headers:get("Content-Type", true)
  116. if type(content_type) == "table" then
  117. content_type = content_type[1]
  118. end
  119. if content_type and content_type:find("image") then
  120. local fp = io.open(cache_file, "wb")
  121. local blob = res.body
  122. fp:write(blob)
  123. fp:close()
  124. return image_loader.decode_float(blob)
  125. end
  126. end
  127. end
  128. return nil, nil
  129. end
  130. local function get_image(req)
  131. local file_info = req:get_arguments("file")
  132. local url = req:get_argument("url", "")
  133. local file = nil
  134. local filename = nil
  135. if file_info and #file_info == 1 then
  136. file = file_info[1][1]
  137. local disp = file_info[1]["content-disposition"]
  138. if disp and disp["filename"] then
  139. filename = path.basename(disp["filename"])
  140. end
  141. end
  142. if file and file:len() > 0 then
  143. local x, meta = image_loader.decode_float(file)
  144. return x, meta, filename
  145. elseif url and url:len() > 0 then
  146. local x, meta = cache_url(url)
  147. return x, meta, filename
  148. end
  149. return nil, nil, nil
  150. end
  151. local function cleanup_model(model)
  152. if CLEANUP_MODEL then
  153. model:clearState() -- release GPU memory
  154. end
  155. end
  156. local function convert(x, meta, options)
  157. local cache_file = path.join(CACHE_DIR, options.prefix .. ".png")
  158. local alpha_cache_file = path.join(CACHE_DIR, options.alpha_prefix .. ".png")
  159. local alpha = meta.alpha
  160. local alpha_orig = alpha
  161. if path.exists(alpha_cache_file) then
  162. alpha = image_loader.load_float(alpha_cache_file)
  163. if alpha:dim() == 2 then
  164. alpha = alpha:reshape(1, alpha:size(1), alpha:size(2))
  165. end
  166. if alpha:size(1) == 3 then
  167. alpha = image.rgb2y(alpha)
  168. end
  169. end
  170. if path.exists(cache_file) then
  171. x = image_loader.load_float(cache_file)
  172. meta = tablex.copy(meta)
  173. meta.alpha = alpha
  174. return x, meta
  175. else
  176. local model = nil
  177. if options.style == "art" then
  178. model = art_model
  179. elseif options.style == "photo" then
  180. model = photo_model
  181. end
  182. if options.border then
  183. x = alpha_util.make_border(x, alpha_orig, reconstruct.offset_size(model.scale))
  184. end
  185. if (options.method == "scale" or
  186. options.method == "noise1_scale" or
  187. options.method == "noise2_scale" or
  188. options.method == "noise3_scale")
  189. then
  190. x = reconstruct.scale_tta(model[options.method], options.tta_level, 2.0, x,
  191. opt.crop_size, opt.batch_size)
  192. if alpha then
  193. if not (alpha:size(2) == x:size(2) and alpha:size(3) == x:size(3)) then
  194. alpha = reconstruct.scale(model.scale, 2.0, alpha,
  195. opt.crop_size, opt.batch_size)
  196. image_loader.save_png(alpha_cache_file, alpha)
  197. cleanup_model(model.scale)
  198. end
  199. end
  200. cleanup_model(model[options.method])
  201. elseif (options.method == "noise1" or
  202. options.method == "noise2" or
  203. options.method == "noise3")
  204. then
  205. x = reconstruct.image_tta(model[options.method], options.tta_level,
  206. x, opt.crop_size, opt.batch_size)
  207. cleanup_model(model[options.method])
  208. end
  209. image_loader.save_png(cache_file, x)
  210. meta = tablex.copy(meta)
  211. meta.alpha = alpha
  212. return x, meta
  213. end
  214. end
  215. local function client_disconnected(handler)
  216. return not(handler.request and
  217. handler.request.connection and
  218. handler.request.connection.stream and
  219. (not handler.request.connection.stream:closed()))
  220. end
  221. local function make_output_filename(filename, mode)
  222. local e = path.extension(filename)
  223. local base = filename:sub(0, filename:len() - e:len())
  224. if mode then
  225. return base .. "_waifu2x_" .. mode .. ".png"
  226. else
  227. return base .. ".png"
  228. end
  229. end
  230. local APIHandler = class("APIHandler", turbo.web.RequestHandler)
  231. function APIHandler:post()
  232. if client_disconnected(self) then
  233. self:set_status(400)
  234. self:write("client disconnected")
  235. return
  236. end
  237. local x, meta, filename = get_image(self)
  238. local scale = tonumber(self:get_argument("scale", "0"))
  239. local noise = tonumber(self:get_argument("noise", "0"))
  240. local tta_level = tonumber(self:get_argument("tta_level", "1"))
  241. local style = self:get_argument("style", "art")
  242. local download = (self:get_argument("download", "")):len()
  243. if tta_level == 0 then
  244. tta_level = auto_tta_level(x, scale)
  245. end
  246. if not (tta_level == 0 or tta_level == 1 or tta_level == 2 or tta_level == 4 or tta_level == 8) then
  247. tta_level = 1
  248. end
  249. if style ~= "art" then
  250. style = "photo" -- style must be art or photo
  251. end
  252. if x and valid_size(x, scale, tta_level) then
  253. local prefix = nil
  254. if (noise ~= 0 or scale ~= 0) then
  255. local hash = md5.sumhexa(meta.blob)
  256. local alpha_prefix = style .. "_" .. hash .. "_alpha"
  257. local border = false
  258. if scale ~= 0 and meta.alpha then
  259. border = true
  260. end
  261. if (scale == 1 or scale == 2) and (noise == 0) then
  262. prefix = style .. "_scale_tta_" .. tta_level .. "_"
  263. x, meta = convert(x, meta, {method = "scale",
  264. style = style,
  265. tta_level = tta_level,
  266. prefix = prefix .. hash,
  267. alpha_prefix = alpha_prefix,
  268. border = border})
  269. if scale == 1 then
  270. x = iproc.scale(x, x:size(3) * (1.6 / 2.0), x:size(2) * (1.6 / 2.0), "Sinc")
  271. end
  272. elseif (scale == 1 or scale == 2) and (noise == 1 or noise == 2 or noise == 3) then
  273. prefix = style .. string.format("_noise%d_scale_tta_", noise) .. tta_level .. "_"
  274. x, meta = convert(x, meta, {method = string.format("noise%d_scale", noise),
  275. style = style,
  276. tta_level = tta_level,
  277. prefix = prefix .. hash,
  278. alpha_prefix = alpha_prefix,
  279. border = border})
  280. if scale == 1 then
  281. x = iproc.scale(x, x:size(3) * (1.6 / 2.0), x:size(2) * (1.6 / 2.0), "Sinc")
  282. end
  283. elseif (noise == 1 or noise == 2 or noise == 3) then
  284. prefix = style .. string.format("_noise%d_tta_", noise) .. tta_level .. "_"
  285. x = convert(x, meta, {method = string.format("noise%d", noise),
  286. style = style,
  287. tta_level = tta_level,
  288. prefix = prefix .. hash,
  289. alpha_prefix = alpha_prefix,
  290. border = border})
  291. border = false
  292. end
  293. end
  294. local name = nil
  295. if filename then
  296. if prefix then
  297. name = make_output_filename(filename, prefix:sub(0, prefix:len()-1))
  298. else
  299. name = make_output_filename(filename, nil)
  300. end
  301. else
  302. name = uuid() .. ".png"
  303. end
  304. local blob = image_loader.encode_png(alpha_util.composite(x, meta.alpha),
  305. tablex.update({depth = 8, inplace = true}, meta))
  306. self:set_header("Content-Length", string.format("%d", #blob))
  307. if download > 0 then
  308. self:set_header("Content-Type", "application/octet-stream")
  309. self:set_header("Content-Disposition", string.format('attachment; filename="%s"', name))
  310. else
  311. self:set_header("Content-Type", "image/png")
  312. self:set_header("Content-Disposition", string.format('inline; filename="%s"', name))
  313. end
  314. self:write(blob)
  315. else
  316. if not x then
  317. self:set_status(400)
  318. self:write("ERROR: An error occurred. (unsupported image format/connection timeout/file is too large)")
  319. else
  320. self:set_status(400)
  321. self:write("ERROR: image size exceeds maximum allowable size.")
  322. end
  323. end
  324. collectgarbage()
  325. end
  326. local FormHandler = class("FormHandler", turbo.web.RequestHandler)
  327. local index_ja = file.read(path.join(ROOT, "assets", "index.ja.html"))
  328. local index_ru = file.read(path.join(ROOT, "assets", "index.ru.html"))
  329. local index_pt = file.read(path.join(ROOT, "assets", "index.pt.html"))
  330. local index_es = file.read(path.join(ROOT, "assets", "index.es.html"))
  331. local index_fr = file.read(path.join(ROOT, "assets", "index.fr.html"))
  332. local index_de = file.read(path.join(ROOT, "assets", "index.de.html"))
  333. local index_tr = file.read(path.join(ROOT, "assets", "index.tr.html"))
  334. local index_zh_cn = file.read(path.join(ROOT, "assets", "index.zh-CN.html"))
  335. local index_en = file.read(path.join(ROOT, "assets", "index.html"))
  336. function FormHandler:get()
  337. local lang = self.request.headers:get("Accept-Language")
  338. if lang then
  339. local langs = utils.split(lang, ",")
  340. for i = 1, #langs do
  341. langs[i] = utils.split(langs[i], ";")[1]
  342. end
  343. if langs[1] == "ja" then
  344. self:write(index_ja)
  345. elseif langs[1] == "ru" then
  346. self:write(index_ru)
  347. elseif langs[1] == "pt" or langs[1] == "pt-BR" then
  348. self:write(index_pt)
  349. elseif langs[1] == "es" or langs[1] == "es-ES" then
  350. self:write(index_es)
  351. elseif langs[1] == "fr" then
  352. self:write(index_fr)
  353. elseif langs[1] == "de" then
  354. self:write(index_de)
  355. elseif langs[1] == "tr" then
  356. self:write(index_tr)
  357. elseif langs[1] == "zh-CN" or langs[1] == "zh" then
  358. self:write(index_zh_cn)
  359. else
  360. self:write(index_en)
  361. end
  362. else
  363. self:write(index_en)
  364. end
  365. end
  366. turbo.log.categories = {
  367. ["success"] = true,
  368. ["notice"] = false,
  369. ["warning"] = true,
  370. ["error"] = true,
  371. ["debug"] = false,
  372. ["development"] = false
  373. }
  374. local app = turbo.web.Application:new(
  375. {
  376. {"^/$", FormHandler},
  377. {"^/api$", APIHandler},
  378. {"^/([%a%d%.%-_]+)$", turbo.web.StaticFileHandler, path.join(ROOT, "assets/")},
  379. }
  380. )
  381. app:listen(opt.port, "0.0.0.0", {max_body_size = CURL_MAX_SIZE})
  382. turbo.ioloop.instance():start()