web.lua 12 KB

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