AutospamService.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Cache;
  4. use Illuminate\Support\Facades\Storage;
  5. use App\Util\Lexer\Classifier;
  6. class AutospamService
  7. {
  8. const CHCKD_CACHE_KEY = 'pf:services:autospam:nlp:checked';
  9. const MODEL_CACHE_KEY = 'pf:services:autospam:nlp:model-cache';
  10. const MODEL_FILE_PATH = 'nlp/active-training-data.json';
  11. const MODEL_SPAM_PATH = 'nlp/spam.json';
  12. const MODEL_HAM_PATH = 'nlp/ham.json';
  13. public static function check($text)
  14. {
  15. if(!$text || strlen($text) == 0) {
  16. false;
  17. }
  18. if(!self::active()) {
  19. return null;
  20. }
  21. $model = self::getCachedModel();
  22. $classifier = new Classifier;
  23. $classifier->import($model['documents'], $model['words']);
  24. return $classifier->most($text) === 'spam';
  25. }
  26. public static function eligible()
  27. {
  28. return Cache::remember(self::CHCKD_CACHE_KEY, 86400, function() {
  29. if(!config_cache('pixelfed.bouncer.enabled') || !config('autospam.enabled')) {
  30. return false;
  31. }
  32. if(!Storage::exists(self::MODEL_SPAM_PATH)) {
  33. return false;
  34. }
  35. if(!Storage::exists(self::MODEL_HAM_PATH)) {
  36. return false;
  37. }
  38. if(!Storage::exists(self::MODEL_FILE_PATH)) {
  39. return false;
  40. } else {
  41. if(Storage::size(self::MODEL_FILE_PATH) < 1000) {
  42. return false;
  43. }
  44. }
  45. return true;
  46. });
  47. }
  48. public static function active()
  49. {
  50. return config_cache('autospam.nlp.enabled') && self::eligible();
  51. }
  52. public static function getCachedModel()
  53. {
  54. if(!self::active()) {
  55. return null;
  56. }
  57. return Cache::remember(self::MODEL_CACHE_KEY, 86400, function() {
  58. $res = Storage::get(self::MODEL_FILE_PATH);
  59. if(!$res || empty($res)) {
  60. return null;
  61. }
  62. return json_decode($res, true);
  63. });
  64. }
  65. }