AutospamService.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Services;
  3. use App\Util\Lexer\Classifier;
  4. use Illuminate\Support\Facades\Cache;
  5. use Illuminate\Support\Facades\Storage;
  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. }
  17. if (! self::active()) {
  18. return null;
  19. }
  20. $model = self::getCachedModel();
  21. $classifier = new Classifier;
  22. $classifier->import($model['documents'], $model['words']);
  23. return $classifier->most($text) === 'spam';
  24. }
  25. public static function eligible()
  26. {
  27. return Cache::remember(self::CHCKD_CACHE_KEY, 86400, function () {
  28. if (! (bool) config_cache('pixelfed.bouncer.enabled') || ! (bool) config_cache('autospam.enabled')) {
  29. return false;
  30. }
  31. if (! Storage::exists(self::MODEL_SPAM_PATH)) {
  32. return false;
  33. }
  34. if (! Storage::exists(self::MODEL_HAM_PATH)) {
  35. return false;
  36. }
  37. if (! Storage::exists(self::MODEL_FILE_PATH)) {
  38. return false;
  39. } else {
  40. if (Storage::size(self::MODEL_FILE_PATH) < 1000) {
  41. return false;
  42. }
  43. }
  44. return true;
  45. });
  46. }
  47. public static function active()
  48. {
  49. return config_cache('autospam.nlp.enabled') && self::eligible();
  50. }
  51. public static function getCachedModel()
  52. {
  53. if (! self::active()) {
  54. return null;
  55. }
  56. return Cache::remember(self::MODEL_CACHE_KEY, 86400, function () {
  57. $res = Storage::get(self::MODEL_FILE_PATH);
  58. if (! $res || empty($res)) {
  59. return null;
  60. }
  61. return json_decode($res, true);
  62. });
  63. }
  64. }