You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lua_nn.lua 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. --[[
  2. Copyright (c) 2017, Vsevolod Stakhov <vsevolod@highsecure.ru>
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ]]--
  13. local rspamd_logger = require "rspamd_logger"
  14. local torch
  15. local exports = {}
  16. local lua_nn_models = {}
  17. local conf_section = rspamd_config:get_all_opt("nn_models")
  18. if conf_section then
  19. if rspamd_config:has_torch() then
  20. torch = require "torch"
  21. torch.setnumthreads(1)
  22. end
  23. end
  24. if torch then
  25. exports.load_rspamd_nn = function()
  26. local function gen_process_callback(name)
  27. return function(str)
  28. if str then
  29. local f = torch.MemoryFile(torch.CharStorage():string(str))
  30. local ret, tnn_or_err = pcall(function() f:readObject() end)
  31. if not ret then
  32. rspamd_logger.errx(rspamd_config, "cannot load neural net model %s: %s",
  33. name, tnn_or_err)
  34. else
  35. rspamd_logger.infox(rspamd_config, "loaded NN model %s: %s bytes",
  36. name, #str)
  37. lua_nn_models[name] = tnn_or_err
  38. end
  39. end
  40. end
  41. end
  42. if conf_section and type(conf_section) == 'table' then
  43. for k,v in pairs(conf_section) do
  44. if not rspamd_config:add_map(v, "nn map " .. k, gen_process_callback(k)) then
  45. rspamd_logger.warnx(rspamd_config, 'cannot load NN map %1', k)
  46. end
  47. end
  48. end
  49. end
  50. exports.try_rspamd_nn = function(name, input)
  51. if not lua_nn_models.name then
  52. return false, 0.0
  53. else
  54. local ret, res_or_err = pcall(function() lua_nn_models.name:forward(input) end)
  55. if not ret then
  56. rspamd_logger.errx(rspamd_config, "cannot run neural net model %s: %s",
  57. name, res_or_err)
  58. else
  59. return true, tonumber(res_or_err)
  60. end
  61. end
  62. return false, 0.0
  63. end
  64. else
  65. exports.load_rspamd_nn = function()
  66. end
  67. exports.try_rspamd_nn = function(name, input)
  68. return false,0.0
  69. end
  70. end
  71. return exports