web.lua 13 KB

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