web.lua 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. return x, {alpha = alpha, gamma = meta.gamma, blob = meta.blob}
  136. else
  137. if options.style == "art" then
  138. if options.border then
  139. x = alpha_util.make_border(x, alpha_orig, reconstruct.offset_size(art_scale2_model))
  140. end
  141. if options.method == "scale" then
  142. x = reconstruct.scale(art_scale2_model, 2.0, x,
  143. opt.crop_size, opt.upsampling_filter)
  144. if alpha then
  145. if not (alpha:size(2) == x:size(2) and alpha:size(3) == x:size(3)) then
  146. alpha = reconstruct.scale(art_scale2_model, 2.0, alpha,
  147. opt.crop_size, opt.upsampling_filter)
  148. image_loader.save_png(alpha_cache_file, alpha)
  149. end
  150. end
  151. cleanup_model(art_scale2_model)
  152. elseif options.method == "noise1" then
  153. x = reconstruct.image(art_noise1_model, x)
  154. cleanup_model(art_noise1_model)
  155. elseif options.method == "noise2" then
  156. x = reconstruct.image(art_noise2_model, x)
  157. cleanup_model(art_noise2_model)
  158. elseif options.method == "noise3" then
  159. x = reconstruct.image(art_noise3_model, x)
  160. cleanup_model(art_noise3_model)
  161. end
  162. else -- photo
  163. if options.border then
  164. x = alpha_util.make_border(x, alpha, reconstruct.offset_size(photo_scale2_model))
  165. end
  166. if options.method == "scale" then
  167. x = reconstruct.scale(photo_scale2_model, 2.0, x,
  168. opt.crop_size, opt.upsampling_filter)
  169. if alpha then
  170. if not (alpha:size(2) == x:size(2) and alpha:size(3) == x:size(3)) then
  171. alpha = reconstruct.scale(photo_scale2_model, 2.0, alpha,
  172. opt.crop_size, opt.upsampling_filter)
  173. image_loader.save_png(alpha_cache_file, alpha)
  174. end
  175. end
  176. cleanup_model(photo_scale2_model)
  177. elseif options.method == "noise1" then
  178. x = reconstruct.image(photo_noise1_model, x)
  179. cleanup_model(photo_noise1_model)
  180. elseif options.method == "noise2" then
  181. x = reconstruct.image(photo_noise2_model, x)
  182. cleanup_model(photo_noise2_model)
  183. elseif options.method == "noise3" then
  184. x = reconstruct.image(photo_noise3_model, x)
  185. cleanup_model(photo_noise3_model)
  186. end
  187. end
  188. image_loader.save_png(cache_file, x)
  189. return x, {alpha = alpha, gamma = meta.gamma, blob = meta.blob}
  190. end
  191. end
  192. local function client_disconnected(handler)
  193. return not(handler.request and
  194. handler.request.connection and
  195. handler.request.connection.stream and
  196. (not handler.request.connection.stream:closed()))
  197. end
  198. local function make_output_filename(filename, mode)
  199. local e = path.extension(filename)
  200. local base = filename:sub(0, filename:len() - e:len())
  201. if mode then
  202. return base .. "_waifu2x_" .. mode .. ".png"
  203. else
  204. return base .. ".png"
  205. end
  206. end
  207. local APIHandler = class("APIHandler", turbo.web.RequestHandler)
  208. function APIHandler:post()
  209. if client_disconnected(self) then
  210. self:set_status(400)
  211. self:write("client disconnected")
  212. return
  213. end
  214. local x, meta, filename = get_image(self)
  215. local scale = tonumber(self:get_argument("scale", "0"))
  216. local noise = tonumber(self:get_argument("noise", "0"))
  217. local style = self:get_argument("style", "art")
  218. local download = (self:get_argument("download", "")):len()
  219. if style ~= "art" then
  220. style = "photo" -- style must be art or photo
  221. end
  222. if x and valid_size(x, scale) then
  223. local prefix = nil
  224. if (noise ~= 0 or scale ~= 0) then
  225. local hash = md5.sumhexa(meta.blob)
  226. local alpha_prefix = style .. "_" .. hash .. "_alpha"
  227. local border = false
  228. if scale ~= 0 and meta.alpha then
  229. border = true
  230. end
  231. if noise == 1 then
  232. prefix = style .. "_noise1_"
  233. x = convert(x, meta, {method = "noise1", style = style,
  234. prefix = prefix .. hash,
  235. alpha_prefix = alpha_prefix, border = border})
  236. border = false
  237. elseif noise == 2 then
  238. prefix = style .. "_noise2_"
  239. x = convert(x, meta, {method = "noise2", style = style,
  240. prefix = prefix .. hash,
  241. alpha_prefix = alpha_prefix, border = border})
  242. border = false
  243. elseif noise == 3 then
  244. prefix = style .. "_noise3_"
  245. x = convert(x, meta, {method = "noise3", style = style,
  246. prefix = prefix .. hash,
  247. alpha_prefix = alpha_prefix, border = border})
  248. border = false
  249. end
  250. if scale == 1 or scale == 2 then
  251. if noise == 1 then
  252. prefix = style .. "_noise1_scale_"
  253. elseif noise == 2 then
  254. prefix = style .. "_noise2_scale_"
  255. elseif noise == 3 then
  256. prefix = style .. "_noise3_scale_"
  257. else
  258. prefix = style .. "_scale_"
  259. end
  260. x, meta = convert(x, meta, {method = "scale", style = style, prefix = prefix .. hash, alpha_prefix = alpha_prefix, border = border})
  261. if scale == 1 then
  262. x = iproc.scale(x, x:size(3) * (1.6 / 2.0), x:size(2) * (1.6 / 2.0), "Sinc")
  263. end
  264. end
  265. end
  266. local name = nil
  267. if filename then
  268. if prefix then
  269. name = make_output_filename(filename, prefix:sub(0, prefix:len()-1))
  270. else
  271. name = make_output_filename(filename, nil)
  272. end
  273. else
  274. name = uuid() .. ".png"
  275. end
  276. local blob = image_loader.encode_png(alpha_util.composite(x, meta.alpha),
  277. { depth = 8, inplace = true, gamma = meta.gamma})
  278. self:set_header("Content-Length", string.format("%d", #blob))
  279. if download > 0 then
  280. self:set_header("Content-Type", "application/octet-stream")
  281. self:set_header("Content-Disposition", string.format('attachment; filename="%s"', name))
  282. else
  283. self:set_header("Content-Type", "image/png")
  284. self:set_header("Content-Disposition", string.format('inline; filename="%s"', name))
  285. end
  286. self:write(blob)
  287. else
  288. if not x then
  289. self:set_status(400)
  290. self:write("ERROR: An error occurred. (unsupported image format/connection timeout/file is too large)")
  291. else
  292. self:set_status(400)
  293. self:write("ERROR: image size exceeds maximum allowable size.")
  294. end
  295. end
  296. collectgarbage()
  297. end
  298. local FormHandler = class("FormHandler", turbo.web.RequestHandler)
  299. local index_ja = file.read(path.join(ROOT, "assets", "index.ja.html"))
  300. local index_ru = file.read(path.join(ROOT, "assets", "index.ru.html"))
  301. local index_pt = file.read(path.join(ROOT, "assets", "index.pt.html"))
  302. local index_es = file.read(path.join(ROOT, "assets", "index.es.html"))
  303. local index_fr = file.read(path.join(ROOT, "assets", "index.fr.html"))
  304. local index_de = file.read(path.join(ROOT, "assets", "index.de.html"))
  305. local index_tr = file.read(path.join(ROOT, "assets", "index.tr.html"))
  306. local index_en = file.read(path.join(ROOT, "assets", "index.html"))
  307. function FormHandler:get()
  308. local lang = self.request.headers:get("Accept-Language")
  309. if lang then
  310. local langs = utils.split(lang, ",")
  311. for i = 1, #langs do
  312. langs[i] = utils.split(langs[i], ";")[1]
  313. end
  314. if langs[1] == "ja" then
  315. self:write(index_ja)
  316. elseif langs[1] == "ru" then
  317. self:write(index_ru)
  318. elseif langs[1] == "pt" or langs[1] == "pt-BR" then
  319. self:write(index_pt)
  320. elseif langs[1] == "es" or langs[1] == "es-ES" then
  321. self:write(index_es)
  322. elseif langs[1] == "fr" then
  323. self:write(index_fr)
  324. elseif langs[1] == "de" then
  325. self:write(index_de)
  326. elseif langs[1] == "tr" then
  327. self:write(index_tr)
  328. else
  329. self:write(index_en)
  330. end
  331. else
  332. self:write(index_en)
  333. end
  334. end
  335. turbo.log.categories = {
  336. ["success"] = true,
  337. ["notice"] = false,
  338. ["warning"] = true,
  339. ["error"] = true,
  340. ["debug"] = false,
  341. ["development"] = false
  342. }
  343. local app = turbo.web.Application:new(
  344. {
  345. {"^/$", FormHandler},
  346. {"^/api$", APIHandler},
  347. {"^/([%a%d%.%-_]+)$", turbo.web.StaticFileHandler, path.join(ROOT, "assets/")},
  348. }
  349. )
  350. app:listen(opt.port, "0.0.0.0", {max_body_size = CURL_MAX_SIZE})
  351. turbo.ioloop.instance():start()