* spam-stat.el (with-syntax-table): Remove with-syntax-table
[gnus] / lisp / spam-stat.el
1 ;;; spam-stat.el --- detecting spam based on statistics
2
3 ;; Copyright (C) 2002, 2003 Free Software Foundation, Inc.
4
5 ;; Author: Alex Schroeder <alex@gnu.org>
6 ;; Keywords: network
7 ;; URL: http://www.emacswiki.org/cgi-bin/wiki.pl?SpamStat
8
9 ;; This file is part of GNU Emacs.
10
11 ;; This is free software; you can redistribute it and/or modify it
12 ;; under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; This is distributed in the hope that it will be useful, but WITHOUT
17 ;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 ;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
19 ;; License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;; This implements spam analysis according to Paul Graham in "A Plan
29 ;; for Spam".  The basis for all this is a statistical distribution of
30 ;; words for your spam and non-spam mails.  We need this information
31 ;; in a hash-table so that the analysis can use the information when
32 ;; looking at your mails.  Therefore, before you begin, you need tons
33 ;; of mails (Graham uses 4000 non-spam and 4000 spam mails for his
34 ;; experiments).
35 ;;
36 ;; The main interface to using spam-stat, are the following functions:
37 ;;
38 ;; `spam-stat-buffer-is-spam' -- called in a buffer, that buffer is
39 ;; considered to be a new spam mail; use this for new mail that has
40 ;; not been processed before
41 ;;
42 ;; `spam-stat-buffer-is-non-spam' -- called in a buffer, that buffer
43 ;; is considered to be a new non-spam mail; use this for new mail that
44 ;; has not been processed before
45 ;;
46 ;; `spam-stat-buffer-change-to-spam' -- called in a buffer, that
47 ;; buffer is no longer considered to be normal mail but spam; use this
48 ;; to change the status of a mail that has already been processed as
49 ;; non-spam
50 ;;
51 ;; `spam-stat-buffer-change-to-non-spam' -- called in a buffer, that
52 ;; buffer is no longer considered to be spam but normal mail; use this
53 ;; to change the status of a mail that has already been processed as
54 ;; spam
55 ;;
56 ;; `spam-stat-save' -- save the hash table to the file; the filename
57 ;; used is stored in the variable `spam-stat-file'
58 ;;
59 ;; `spam-stat-load' -- load the hash table from a file; the filename
60 ;; used is stored in the variable `spam-stat-file'
61 ;;
62 ;; `spam-stat-score-word' -- return the spam score for a word
63 ;;
64 ;; `spam-stat-score-buffer' -- return the spam score for a buffer
65 ;;
66 ;; `spam-stat-split-fancy' -- for fancy mail splitting; add
67 ;; the rule (: spam-stat-split-fancy) to `nnmail-split-fancy'
68 ;;
69 ;; This requires the following in your ~/.gnus file:
70 ;;
71 ;; (require 'spam-stat)
72 ;; (spam-stat-load)
73
74 ;;; Testing:
75
76 ;; Typical test will involve calls to the following functions:
77 ;;
78 ;; Reset: (spam-stat-reset)
79 ;; Learn spam: (spam-stat-process-spam-directory "~/Mail/mail/spam")
80 ;; Learn non-spam: (spam-stat-process-non-spam-directory "~/Mail/mail/misc")
81 ;; Save table: (spam-stat-save)
82 ;; File size: (nth 7 (file-attributes spam-stat-file))
83 ;; Number of words: (hash-table-count spam-stat)
84 ;; Test spam: (spam-stat-test-directory "~/Mail/mail/spam")
85 ;; Test non-spam: (spam-stat-test-directory "~/Mail/mail/misc")
86 ;; Reduce table size: (spam-stat-reduce-size)
87 ;; Save table: (spam-stat-save)
88 ;; File size: (nth 7 (file-attributes spam-stat-file))
89 ;; Number of words: (hash-table-count spam-stat)
90 ;; Test spam: (spam-stat-test-directory "~/Mail/mail/spam")
91 ;; Test non-spam: (spam-stat-test-directory "~/Mail/mail/misc")
92
93 ;;; Dictionary Creation:
94
95 ;; Typically, you will filter away mailing lists etc. using specific
96 ;; rules in `nnmail-split-fancy'.  Somewhere among these rules, you
97 ;; will filter spam.  Here is how you would create your dictionary:
98
99 ;; Reset: (spam-stat-reset)
100 ;; Learn spam: (spam-stat-process-spam-directory "~/Mail/mail/spam")
101 ;; Learn non-spam: (spam-stat-process-non-spam-directory "~/Mail/mail/misc")
102 ;; Repeat for any other non-spam group you need...
103 ;; Reduce table size: (spam-stat-reduce-size)
104 ;; Save table: (spam-stat-save)
105
106 ;;; Todo:
107
108 ;; Speed it up.  Integrate with Gnus such that it uses spam and expiry
109 ;; marks to call the appropriate functions when leaving the summary
110 ;; buffer and saves the hash table when leaving Gnus.  More testing:
111 ;; More mails, disabling SpamAssassin, double checking algorithm, find
112 ;; improved algorithm.
113
114 ;;; Thanks:
115
116 ;; Ted Zlatanov <tzz@lifelogs.com>
117 ;; Jesper Harder <harder@myrealbox.com>
118 ;; Dan Schmidt <dfan@dfan.org>
119 ;; Lasse Rasinen <lrasinen@iki.fi>
120 ;; Milan Zamazal <pdm@zamazal.org>
121
122 \f
123
124 ;;; Code:
125
126 (defgroup spam-stat nil
127   "Statistical spam detection for Emacs.
128 Use the functions to build a dictionary of words and their statistical
129 distribution in spam and non-spam mails.  Then use a function to determine
130 whether a buffer contains spam or not."
131   :group 'gnus)
132
133 (defcustom spam-stat-file "~/.spam-stat.el"
134   "File used to save and load the dictionary.
135 See `spam-stat-to-hash-table' for the format of the file."
136   :type 'file
137   :group 'spam-stat)
138
139 (defcustom spam-stat-install-hooks t
140   "Whether spam-stat should install its hooks in Gnus.
141 This is set to nil if you use spam-stat through spam.el."
142   :type 'boolean
143   :group 'spam-stat)
144
145 (defcustom spam-stat-unknown-word-score 0.2
146   "The score to use for unknown words.
147 Also used for words that don't appear often enough."
148   :type 'number
149   :group 'spam-stat)
150
151 (defcustom spam-stat-max-word-length 15
152   "Only words shorter than this will be considered."
153   :type 'integer
154   :group 'spam-stat)
155
156 (defcustom spam-stat-max-buffer-length 10240
157   "Only the beginning of buffers will be analyzed.
158 This variable says how many characters this will be."
159   :type 'integer
160   :group 'spam-stat)
161
162 (defcustom spam-stat-split-fancy-spam-group "mail.spam"
163   "Name of the group where spam should be stored, if
164 `spam-stat-split-fancy' is used in fancy splitting rules.  Has no
165 effect when spam-stat is invoked through spam.el."
166   :type 'string
167   :group 'spam-stat)
168
169 (defcustom spam-stat-split-fancy-spam-threshhold 0.9
170   "Spam score threshhold in spam-stat-split-fancy."
171   :type 'number
172   :group 'spam-stat)
173
174 (defvar spam-stat-syntax-table
175   (let ((table (copy-syntax-table text-mode-syntax-table)))
176     (modify-syntax-entry ?- "w" table)
177     (modify-syntax-entry ?_ "w" table)
178     (modify-syntax-entry ?. "w" table)
179     (modify-syntax-entry ?! "w" table)
180     (modify-syntax-entry ?? "w" table)
181     (modify-syntax-entry ?+ "w" table)
182     table)
183   "Syntax table used when processing mails for statistical analysis.
184 The important part is which characters are word constituents.")
185
186 (defvar spam-stat-dirty nil
187   "Whether the spam-stat database needs saving.")
188
189 (defvar spam-stat-buffer nil
190   "Buffer to use for scoring while splitting.
191 This is set by hooking into Gnus.")
192
193 (defvar spam-stat-buffer-name " *spam stat buffer*"
194   "Name of the `spam-stat-buffer'.")
195
196 ;; Functions missing in Emacs 20
197
198 (when (memq nil (mapcar 'fboundp
199                         '(gethash hash-table-count make-hash-table
200                                   mapc puthash)))
201   (require 'cl)
202   (unless (fboundp 'puthash)
203     ;; alias puthash is missing from Emacs 20 cl-extra.el
204     (defalias 'puthash 'cl-puthash)))
205
206 ;; Hooking into Gnus
207
208 (defun spam-stat-store-current-buffer ()
209   "Store a copy of the current buffer in `spam-stat-buffer'."
210   (save-excursion
211     (let ((str (buffer-string)))
212       (set-buffer (get-buffer-create spam-stat-buffer-name))
213       (erase-buffer)
214       (insert str)
215       (setq spam-stat-buffer (current-buffer)))))
216
217 (defun spam-stat-store-gnus-article-buffer ()
218   "Store a copy of the current article in `spam-stat-buffer'.
219 This uses `gnus-article-buffer'."
220   (save-excursion
221     (set-buffer gnus-original-article-buffer)
222     (spam-stat-store-current-buffer)))
223
224 ;; Data -- not using defstruct in order to save space and time
225
226 (defvar spam-stat (make-hash-table :test 'equal)
227   "Hash table used to store the statistics.
228 Use `spam-stat-load' to load the file.
229 Every word is used as a key in this table.  The value is a vector.
230 Use `spam-stat-ngood', `spam-stat-nbad', `spam-stat-good',
231 `spam-stat-bad', and `spam-stat-score' to access this vector.")
232
233 (defvar spam-stat-ngood 0
234   "The number of good mails in the dictionary.")
235
236 (defvar spam-stat-nbad 0
237   "The number of bad mails in the dictionary.")
238
239 (defsubst spam-stat-good (entry)
240   "Return the number of times this word belongs to good mails."
241   (aref entry 0))
242
243 (defsubst spam-stat-bad (entry)
244   "Return the number of times this word belongs to bad mails."
245   (aref entry 1))
246
247 (defsubst spam-stat-score (entry)
248   "Set the score of this word."
249   (if entry
250       (aref entry 2)
251     spam-stat-unknown-word-score))
252
253 (defsubst spam-stat-set-good (entry value)
254   "Set the number of times this word belongs to good mails."
255   (aset entry 0 value))
256
257 (defsubst spam-stat-set-bad (entry value)
258   "Set the number of times this word belongs to bad mails."
259   (aset entry 1 value))
260
261 (defsubst spam-stat-set-score (entry value)
262   "Set the score of this word."
263   (aset entry 2 value))
264
265 (defsubst spam-stat-make-entry (good bad)
266   "Return a vector with the given properties."
267   (let ((entry (vector good bad nil)))
268     (spam-stat-set-score entry (spam-stat-compute-score entry))
269     entry))
270
271 ;; Computing
272
273 (defun spam-stat-compute-score (entry)
274   "Compute the score of this word.  1.0 means spam."
275    ;; promote all numbers to floats for the divisions
276    (let* ((g (* 2.0 (spam-stat-good entry)))
277           (b (float (spam-stat-bad entry))))
278      (cond ((< (+ g b) 5)
279             .2)
280            ((= 0 spam-stat-ngood)
281             .99)
282            ((= 0 spam-stat-nbad)
283             .01)
284            (t
285             (max .01
286                  (min .99 (/ (/ b spam-stat-nbad)
287                              (+ (/ g spam-stat-ngood)
288                                 (/ b spam-stat-nbad)))))))))
289
290 ;; Parsing
291
292 (defmacro with-spam-stat-max-buffer-size (&rest body)
293   "Narrows the buffer down to the first 4k characters, then evaluates BODY."
294   `(save-restriction
295      (when (> (- (point-max)
296                  (point-min))
297               spam-stat-max-buffer-length)
298        (narrow-to-region (point-min)
299                          (+ (point-min) spam-stat-max-buffer-length)))
300      ,@body))
301
302 (defun spam-stat-buffer-words ()
303   "Return a hash table of words and number of occurences in the buffer."
304   (with-spam-stat-max-buffer-size
305    (with-syntax-table spam-stat-syntax-table
306      (goto-char (point-min))
307      (let ((result (make-hash-table :test 'equal))
308            word count)
309        (while (re-search-forward "\\w+" nil t)
310          (setq word (match-string-no-properties 0)
311                count (1+ (gethash word result 0)))
312          (when (< (length word) spam-stat-max-word-length)
313            (puthash word count result)))
314        result))))
315
316 (defun spam-stat-buffer-is-spam ()
317   "Consider current buffer to be a new spam mail."
318   (setq spam-stat-nbad (1+ spam-stat-nbad))
319   (maphash
320    (lambda (word count)
321      (let ((entry (gethash word spam-stat)))
322        (if entry
323            (spam-stat-set-bad entry (+ count (spam-stat-bad entry)))
324          (setq entry (spam-stat-make-entry 0 count)))
325        (spam-stat-set-score entry (spam-stat-compute-score entry))
326        (puthash word entry spam-stat)))
327    (spam-stat-buffer-words))
328   (setq spam-stat-dirty t))
329
330 (defun spam-stat-buffer-is-non-spam ()
331   "Consider current buffer to be a new non-spam mail."
332   (setq spam-stat-ngood (1+ spam-stat-ngood))
333   (maphash
334    (lambda (word count)
335      (let ((entry (gethash word spam-stat)))
336        (if entry
337            (spam-stat-set-good entry (+ count (spam-stat-good entry)))
338          (setq entry (spam-stat-make-entry count 0)))
339        (spam-stat-set-score entry (spam-stat-compute-score entry))
340        (puthash word entry spam-stat)))
341    (spam-stat-buffer-words))
342   (setq spam-stat-dirty t))
343
344 (defun spam-stat-buffer-change-to-spam ()
345   "Consider current buffer no longer normal mail but spam."
346   (setq spam-stat-nbad (1+ spam-stat-nbad)
347         spam-stat-ngood (1- spam-stat-ngood))
348   (maphash
349    (lambda (word count)
350      (let ((entry (gethash word spam-stat)))
351        (if (not entry)
352            (error "This buffer has unknown words in it.")
353          (spam-stat-set-good entry (- (spam-stat-good entry) count))
354          (spam-stat-set-bad entry (+ (spam-stat-bad entry) count))
355          (spam-stat-set-score entry (spam-stat-compute-score entry))
356          (puthash word entry spam-stat))))
357    (spam-stat-buffer-words))
358   (setq spam-stat-dirty t))
359
360 (defun spam-stat-buffer-change-to-non-spam ()
361   "Consider current buffer no longer spam but normal mail."
362   (setq spam-stat-nbad (1- spam-stat-nbad)
363         spam-stat-ngood (1+ spam-stat-ngood))
364   (maphash
365    (lambda (word count)
366      (let ((entry (gethash word spam-stat)))
367        (if (not entry)
368            (error "This buffer has unknown words in it.")
369          (spam-stat-set-good entry (+ (spam-stat-good entry) count))
370          (spam-stat-set-bad entry (- (spam-stat-bad entry) count))
371          (spam-stat-set-score entry (spam-stat-compute-score entry))
372          (puthash word entry spam-stat))))
373    (spam-stat-buffer-words))
374   (setq spam-stat-dirty t))
375
376 ;; Saving and Loading
377
378 (defun spam-stat-save (&optional force)
379   "Save the `spam-stat' hash table as lisp file."
380   (interactive)
381   (when (or force spam-stat-dirty)
382     (with-temp-buffer
383       (let ((standard-output (current-buffer))
384             (font-lock-maximum-size 0))
385         (insert "(setq spam-stat-ngood "
386                 (number-to-string spam-stat-ngood)
387                 " spam-stat-nbad "
388                 (number-to-string spam-stat-nbad)
389                 " spam-stat (spam-stat-to-hash-table '(")
390         (maphash (lambda (word entry)
391                    (prin1 (list word
392                                 (spam-stat-good entry)
393                                 (spam-stat-bad entry))))
394                  spam-stat)
395         (insert ")))")
396         (write-file spam-stat-file)))
397     (setq spam-stat-dirty nil)))
398
399 (defun spam-stat-load ()
400   "Read the `spam-stat' hash table from disk."
401   ;; TODO: maybe we should warn the user if spam-stat-dirty is t?
402   (load-file spam-stat-file)
403   (setq spam-stat-dirty nil))
404
405 (defun spam-stat-to-hash-table (entries)
406   "Turn list ENTRIES into a hash table and store as `spam-stat'.
407 Every element in ENTRIES has the form \(WORD GOOD BAD) where WORD is
408 the word string, NGOOD is the number of good mails it has appeared in,
409 NBAD is the number of bad mails it has appeared in, GOOD is the number
410 of times it appeared in good mails, and BAD is the number of times it
411 has appeared in bad mails."
412   (let ((table (make-hash-table :test 'equal)))
413     (mapc (lambda (l)
414             (puthash (car l)
415                      (spam-stat-make-entry (nth 1 l) (nth 2 l))
416                      table))
417           entries)
418     table))
419
420 (defun spam-stat-reset ()
421   "Reset `spam-stat' to an empty hash-table.
422 This deletes all the statistics."
423   (interactive)
424   (setq spam-stat (make-hash-table :test 'equal)
425         spam-stat-ngood 0
426         spam-stat-nbad 0)
427   (setq spam-stat-dirty t))
428
429 ;; Scoring buffers
430
431 (defvar spam-stat-score-data nil
432   "Raw data used in the last run of `spam-stat-score-buffer'.")
433
434 (defsubst spam-stat-score-word (word)
435   "Return score for WORD.
436 The default score for unknown words is stored in
437 `spam-stat-unknown-word-score'."
438   (spam-stat-score (gethash word spam-stat)))
439
440 (defun spam-stat-buffer-words-with-scores ()
441   "Process current buffer, return the 15 most conspicuous words.
442 These are the words whose spam-stat differs the most from 0.5.
443 The list returned contains elements of the form \(WORD SCORE DIFF),
444 where DIFF is the difference between SCORE and 0.5."
445   (with-spam-stat-max-buffer-size
446    (with-syntax-table spam-stat-syntax-table
447      (let (result word score)
448        (maphash (lambda (word ignore)
449                   (setq score (spam-stat-score-word word)
450                         result (cons (list word score (abs (- score 0.5)))
451                                      result)))
452                 (spam-stat-buffer-words))
453        (setq result (sort result (lambda (a b) (< (nth 2 b) (nth 2 a)))))
454        (setcdr (nthcdr 14 result) nil)
455        result))))
456
457 (defun spam-stat-score-buffer ()
458   "Return a score describing the spam-probability for this buffer."
459   (setq spam-stat-score-data (spam-stat-buffer-words-with-scores))
460   (let* ((probs (mapcar (lambda (e) (cadr e)) spam-stat-score-data))
461          (prod (apply #'* probs)))
462     (/ prod (+ prod (apply #'* (mapcar #'(lambda (x) (- 1 x))
463                                        probs))))))
464
465 (defun spam-stat-split-fancy ()
466   "Return the name of the spam group if the current mail is spam.
467 Use this function on `nnmail-split-fancy'.  If you are interested in
468 the raw data used for the last run of `spam-stat-score-buffer',
469 check the variable `spam-stat-score-data'."
470   (condition-case var
471       (progn
472         (set-buffer spam-stat-buffer)
473         (goto-char (point-min))
474         (when (> (spam-stat-score-buffer) spam-stat-split-fancy-spam-threshhold)
475           (when (boundp 'nnmail-split-trace)
476             (mapc (lambda (entry)
477                     (push entry nnmail-split-trace))
478                   spam-stat-score-data))
479           spam-stat-split-fancy-spam-group))
480     (error (message "Error in spam-stat-split-fancy: %S" var)
481            nil)))
482
483 ;; Testing
484
485 (defun spam-stat-process-directory (dir func)
486   "Process all the regular files in directory DIR using function FUNC."
487   (let* ((files (directory-files dir t "^[^.]"))
488          (max (/ (length files) 100.0))
489          (count 0))
490     (with-temp-buffer
491       (dolist (f files)
492         (when (and (file-readable-p f)
493                    (file-regular-p f)
494                    (> (nth 7 (file-attributes f)) 0))
495           (setq count (1+ count))
496           (message "Reading %s: %.2f%%" dir (/ count max))
497           (insert-file-contents f)
498           (funcall func)
499           (erase-buffer))))))
500
501 (defun spam-stat-process-spam-directory (dir)
502   "Process all the regular files in directory DIR as spam."
503   (interactive "D")
504   (spam-stat-process-directory dir 'spam-stat-buffer-is-spam))
505
506 (defun spam-stat-process-non-spam-directory (dir)
507   "Process all the regular files in directory DIR as non-spam."
508   (interactive "D")
509   (spam-stat-process-directory dir 'spam-stat-buffer-is-non-spam))
510
511 (defun spam-stat-count ()
512   "Return size of `spam-stat'."
513   (interactive)
514   (hash-table-count spam-stat))
515
516 (defun spam-stat-test-directory (dir)
517   "Test all the regular files in directory DIR for spam.
518 If the result is 1.0, then all files are considered spam.
519 If the result is 0.0, non of the files is considered spam.
520 You can use this to determine error rates."
521   (interactive "D")
522   (let* ((files (directory-files dir t "^[^.]"))
523          (total (length files))
524          (score 0.0); float
525          (max (/ total 100.0)); float
526          (count 0))
527     (with-temp-buffer
528       (dolist (f files)
529         (when (and (file-readable-p f)
530                    (file-regular-p f)
531                    (> (nth 7 (file-attributes f)) 0))
532           (setq count (1+ count))
533           (message "Reading %.2f%%, score %.2f%%"
534                    (/ count max) (/ score count))
535           (insert-file-contents f)
536           (when (> (spam-stat-score-buffer) 0.9)
537             (setq score (1+ score)))
538           (erase-buffer))))
539     (message "Final score: %d / %d = %f" score total (/ score total))))
540
541 ;; Shrinking the dictionary
542
543 (defun spam-stat-reduce-size (&optional count)
544   "Reduce the size of `spam-stat'.
545 This removes all words that occur less than COUNT from the dictionary.
546 COUNT defaults to 5"
547   (interactive)
548   (setq count (or count 5))
549   (maphash (lambda (key entry)
550              (when (< (+ (spam-stat-good entry)
551                          (spam-stat-bad entry))
552                       count)
553                (remhash key spam-stat)))
554            spam-stat))
555
556 (defun spam-stat-install-hooks-function ()
557   "Install the spam-stat function hooks"
558   (interactive)
559   (add-hook 'nnmail-prepare-incoming-message-hook
560             'spam-stat-store-current-buffer)
561   (add-hook 'gnus-select-article-hook
562             'spam-stat-store-gnus-article-buffer))
563
564 (when spam-stat-install-hooks
565   (spam-stat-install-hooks-function))
566
567 (defun spam-stat-unload-hook ()
568   "Uninstall the spam-stat function hooks"
569   (interactive)
570   (remove-hook 'nnmail-prepare-incoming-message-hook
571                'spam-stat-store-current-buffer)
572   (remove-hook 'gnus-select-article-hook
573                'spam-stat-store-gnus-article-buffer))
574
575 (provide 'spam-stat)
576
577 ;;; spam-stat.el ends here