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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. if rspamd_config:has_torch() then
  18. torch = require "torch"
  19. torch.setnumthreads(1)
  20. end
  21. if torch then
  22. exports.load_rspamd_nn = function()
  23. local function gen_process_callback(name)
  24. return function(str)
  25. if str then
  26. local f = torch.MemoryFile(torch.CharStorage():string(str))
  27. local ret, tnn_or_err = pcall(function() f:readObject() end)
  28. if not ret then
  29. rspamd_logger.errx(rspamd_config, "cannot load neural net model %s: %s",
  30. name, tnn_or_err)
  31. else
  32. rspamd_logger.infox(rspamd_config, "loaded NN model %s: %s bytes",
  33. name, #str)
  34. lua_nn_models[name] = tnn_or_err
  35. end
  36. end
  37. end
  38. end
  39. local section = rspamd_config:get_all_opt("nn_models")
  40. if section and type(section) == 'table' then
  41. for k,v in pairs(section) do
  42. if not rspamd_config:add_map(v, "nn map " .. k, gen_process_callback(k)) then
  43. rspamd_logger.warnx(rspamd_config, 'cannot load NN map %1', k)
  44. end
  45. end
  46. end
  47. end
  48. exports.try_rspamd_nn = function(name, input)
  49. if not lua_nn_models.name then
  50. return false, 0.0
  51. else
  52. local ret, res_or_err = pcall(function() lua_nn_models.name:forward(input) end)
  53. if not ret then
  54. rspamd_logger.errx(rspamd_config, "cannot run neural net model %s: %s",
  55. name, res_or_err)
  56. else
  57. return true, tonumber(res_or_err)
  58. end
  59. end
  60. return false, 0.0
  61. end
  62. else
  63. exports.load_rspamd_nn = function()
  64. end
  65. exports.try_rspamd_nn = function(name, input)
  66. return false,0.0
  67. end
  68. end
  69. return exports